首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java文件-更新后的新文件显示在一行中

Java文件-更新后的新文件显示在一行中
EN

Stack Overflow用户
提问于 2012-12-03 18:16:03
回答 1查看 103关注 0票数 0

我正在尝试使用Java使用新数据更新文件。假设我有一个txt文件,其中保存了以下数据:

代码语言:javascript
复制
id     grade
3498   8
2345   9
5444   7
2222   5

因此,我正在尝试更新成绩,具体取决于用户输入的id,但新的(更新后的)文件的类型如下:

代码语言:javascript
复制
id   grade3498   62345   95444   72222   5

以此类推...

我找不到这不起作用的原因,我猜这与重写数据时没有添加新行有关,但即使我在outobj.write(fileContent.toString())中添加新行字符("\n"),也没有什么变化。

下面是我的代码片段:

代码语言:javascript
复制
public String check(int num) throws RemoteException
{
    String textinLine;
    String texttoEdit;
    File file=new File ("c:\\students.txt");
    FileInputStream stream = null;
    DataInputStream in =null;
    BufferedReader br = null;
    try
        {
        stream = new FileInputStream(file);
        in =new DataInputStream(stream);
        br = new BufferedReader(new InputStreamReader(in));
        StringBuilder fileContent = new StringBuilder();
        if ((num>0) && (num<6001))
            {
            while ((textinLine=br.readLine())!=null)
                {
                texttoEdit=Integer.toString(num);
                    System.out.println(textinLine);
                    String[] parts = textinLine.split(" ");
                    if (parts.length>0)
                        {
                        if (parts[0].equals(texttoEdit))
                            {
                            int value =       Integer.parseInt(parts[1]);
                            value-=2;
                            String edit=Integer.toString(value);
                            String newLine = "\n"+parts[0]+"    "+edit+"\n";
                            msg="You can pass2";
                            fileContent.append(newLine);
fileContent.append("\n");               }
                        else
                            {
                            fileContent.append(textinLine);
fileContent.append("\n");
                            }
                        }
                }
            }
        in.close();
        FileWriter fstream = new FileWriter(file);
        BufferedWriter outobj = new BufferedWriter(fstream);
        outobj.write(fileContent.toString());
        outobj.close();
        }
    catch (FileNotFoundException e)
        {
        e.printStackTrace();
        }
    catch (IOException e)
        {
        e.printStackTrace();
        }

最后,假设新文件被正确编辑,这意味着如果用户输入id3498,等级值将更改为8-2=6,但新文件将在一行中,正如我前面解释的那样。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-03 18:16:57

在一些操作系统(通常是Windows)上,您需要使用\r\n来创建新行。更好的是,你可以使用:

代码语言:javascript
复制
String newLine = System.getProperty("line.separator");

对于行分隔符,它将根据运行它的平台进行调整。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13681118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档