0

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) {}

}
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

3 Answers3

3
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.
camickr
  • 321,443
  • 19
  • 166
  • 288
  • "You can't read and write to the same file unless you are using RandomAccessFile" I understand this is true, but only in this specific case since OP wants to write/edit file in between original content. Do you mind specifying the same in your answer, so someone else reading this later who is a learner is not confused. – Polynomial Proton Mar 03 '15 at 22:02
  • 1
    @TheUknown, added some clarification. – camickr Mar 03 '15 at 22:27
1

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();
    }

}

Community
  • 1
  • 1
Faktor 10
  • 1,868
  • 2
  • 21
  • 29
  • Why did you create a new answer? All you had to do was edit your own answer and add the code. Looks to me like this approach reads the entire file into memory. Not a very scalable solution. – camickr Mar 03 '15 at 23:26
-1

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)