简体   繁体   English

在Java中写入文本文件时如何插入换行

[英]How to insert New Lines when Writing to a Text File in Java

I would like to create a simple program (in Java) which edits text files - particularly one which performs inserting arbitrary pieces of text at random positions in a text file. 我想创建一个用于编辑文本文件的简单程序(用Java),尤其是一个可以在文本文件中的任意位置插入任意文本的程序。

Old Text file: 旧文本文件:

Noodles
Cereal
Tomato
Carrot
Fish
Meat

Output: 输出:

Please insert new record:
1
Cornflake

Please insert new record:

New Text File: 新文本文件:

Noodles
Cereal
Tomato
Carrot
Fish
Meat
Cornflake

I check on my text file and it insert into my text file but when I run program again, for example, I want to insert Ice-Cream then it should added after Cornflake but instead it replace Cornflake with Ice-Cream. 我检查了我的文本文件,并将其插入到我的文本文件中,但是,例如,当我再次运行程序时,我想插入Ice-Cream,则应在Cornflake之后添加它,但用Ice-Cream代替Cornflake。 But how can I resolve this problem? 但是我该如何解决这个问题?

Java: Java:

String INPUT_PROMPT ="Please insert new record:";
BufferedReader reader = new BufferedReader
                    (new InputStreamReader (System.in));
            line = reader.readLine();

while(!line.equals("x"))
{ 
          switch(line)
          {       
              case "1":
              line = reader.readLine();  

                    FileWriter fw=new FileWriter(inFile);
                    BufferedWriter bw=new BufferedWriter(fw);
                    PrintWriter pw=new PrintWriter(bw);

                    for(int k=0; k< prdct.size(); k++)
                    {
                        pw.println(prdct.get(k).toString());
                    }
                    pw.write(line);
                    pw.write("\n");
                    pw.close();    
                    break;
          }  
            System.out.println(INPUT_PROMPT);
            line = reader.readLine();  


}

This question is probably a duplicate of many others, but you need to open the FileWriter in append mode, which is done by passing true as the second parameter in the constructor: 这个问题可能是许多其他问题的重复,但是您需要以附加模式打开FileWriter ,这是通过将true作为构造函数中的第二个参数传递来完成的:

FileWriter fw = new FileWriter(inFile, true);

From the Javadoc for FileWriter(File file, boolean append) : Javadoc for FileWriter(文件文件,布尔值附加)

Constructs a FileWriter object given a File object. 给定File对象,构造一个FileWriter对象。 If the second argument is true, then bytes will be written to the end of the file rather than the beginning. 如果第二个参数为true,则字节将被写入文件的末尾而不是开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM