简体   繁体   中英

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.

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. But how can I resolve this problem?

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 fw = new FileWriter(inFile, true);

From the Javadoc for FileWriter(File file, boolean append) :

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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