简体   繁体   中英

Java append to end of each line to a text file

I want to add some text to the end of each line in a existing text file. Everytime I run my code, it erases all content but does not write/append anything to the file. Any help is greatly appreciated.

import java.io.*;

public class RandomNumber 
{
     public static void main(String[] args) {

         File dir = new File("C:\\testing");
         System.out.println(dir.isDirectory());


         try {
              File file = new File(dir, "Test.txt");
              FileReader fr = new FileReader(file);
              BufferedReader br = new BufferedReader(fr);
              FileWriter fw = new FileWriter(file);
              BufferedWriter bw = new BufferedWriter(fw);

              String s = "Add1,";
              String s2 = "Add2\n";
              String str;

              while((str = br.readLine()) != null) {
              StringBuffer sb = new StringBuffer(str);
              sb.append(s + s2);
              String y = sb.toString();
              System.out.println(sb);
              System.out.println("Appending");
              bw.write(y);
              }

              bw.close();
              System.out.println("Done");


         }catch(IOException e) {}

}
}
catch(IOException e) {}

Don't use an empty catch block. You should display a message when there is an Exception.

You can't read and write to the same file unless you are using RandomAccessFile.

When you open the file for ouput, the file is cleared so there in no data to read and therefore no data to write so the result is that the file in now empty.

If you open the file for output in "append" mode then yes you can read the data in the file (and the data will remain in the file) but all the write statements are appended to the end of the original file so effectively you now have a copy of the data in the file.

Instead your basic logic should be:

  1. Read a line from the input file
  2. Write the text to the output file
  3. after reading all the data close both files.
  4. Delete the input file
  5. Rename the output file to be the same name as the input file.

I am not sure what version of Java you are using but if you can I would strongly recommend moving to Java 8 which uses Streams. This is a great functional programming interface and removes heaps of boilerplate code. See Using Java 8, what is the most preferred and concise way of printing all the lines in a file?

which talks about what you are trying to achieve but in a functional way. Ignore my suggestion if this is going to complicate your approach, but I would certainly in the future look into Java 8 and its FP constructs which make coding far more elegant in Java.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class RandomNumber {

public static void main(String[] args) {

    Path path = Paths.get("c:/workspace", "testing.txt");

    String s = "Add1\n";
    try(BufferedWriter writer = Files.newBufferedWriter(path,StandardOpenOption.APPEND)) { 
        writer.write(s);
}
    } catch (IOException e) {
        e.printStackTrace();
    }

}

It seems that you need to re-assign to the string builder after appending to it. Try replacing sb.append(s + s2) by sb = sb.append(s + s2)

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