0

I am trying to read from a file and then writing back to that same while while appending it.

The file to be read has 5,10 and after writing, it the file should have 5,10"\n" 15.

But instead of that it has 5,10"\n" SI.

here is my source code -

 import java.io.*;
 import java.util.*;


public class Ash  {



public static void main(String[] args) throws IOException{

File file = new File("ashray.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
Scanner input = new Scanner(reader);

    String str = input.nextLine();

    String [] sc = str.split(",");

    int x = Integer.parseInt(sc[0]);
    int y = Integer.parseInt(sc[1]);
    int z = x+y;
    input.close();

    FileWriter fw = new FileWriter(file,true);
    BufferedWriter writer = new BufferedWriter(fw);     
    writer.write(Integer.toString(z));

    fw.close();     

   }    
}
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
shiwchiz
  • 43
  • 7

2 Answers2

0

Use the PrintWriter

PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println("print content here");
writer.close();
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
0

The problem is that you are closing the FileWriter rather than the BufferedWriter. This means that your application is exiting with unwritten characters in the BufferedWriter's buffer.

Solution: change

 fw.close();     

to

 writer.close();

Closing the BufferedWriter is going to close the Writer that it wraps. The javadoc says so.

(You don't need to close the Reader. Closing the Scanner will close the source that it wraps. And besides, neither is strictly necessary in this context. But see below.)


Also note that if this was production code, it would be advisable to use try with resources to ensure that the file descriptors were always closed, irrespective of how the method terminated. The issue is that if the method terminated because an exception was thrown, you could skip over the statements that close the Reader or Writer stacks. That could lead to a resource leak and unexpected errors when opening files ... later on.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216