Java文件 - 新更新的文件出现在一行中

Ela*_*aki 0 java newline java-io

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

id     grade
3498   8
2345   9
5444   7
2222   5
Run Code Online (Sandbox Code Playgroud)

所以我试图根据用户键入的id更新成绩,但新的(更新的)文件具有以下类型:

id   grade3498   62345   95444   72222   5
Run Code Online (Sandbox Code Playgroud)

等等....

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

这是我的代码片段:

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();
        }
Run Code Online (Sandbox Code Playgroud)

最后,让我说新文件是正确编辑的,这意味着如果用户输入id 3498,等级值将变为8-2 = 6,但新文件将在一行中,正如我解释的那样之前.

ass*_*ias 6

在某些操作系统(通常是Windows)上,您需要使用\r\n新的线路.更好的是,您可以使用:

String newLine = System.getProperty("line.separator");
Run Code Online (Sandbox Code Playgroud)

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

  • 很好的答案.+1 (3认同)