Good practice in Java File I/O

Happy Mittal picture Happy Mittal · Nov 1, 2012 · Viewed 11.4k times · Source

I am trying to read integers from a file, apply some operation on them and writing those resulting integers to another file.

// Input
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
Scanner s = new Scanner(br);

// Output
FileWriter fw = new FileWriter("out.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);

int i;

while(s.hasNextInt())
{
    i = s.nextInt();
    pw.println(i+5);
}

I want to ask is it a good practice to wrap these input and output streams like this?
I am new to java and on internet, I saw lots of other ways of I/O in files. I want to stick to one approach so is above the best approach ?

Answer

Kumar Vivek Mitra picture Kumar Vivek Mitra · Nov 1, 2012

- Well consider that you went shopping into a food mall, Now what you do usually, pick-up each item from the selves and then go to the billing counter then again go to the selves and back to billing counter ....?? Or Store all the item into a Cart then go to the billing counter.

- Its similar here in Java, Files deal with bytes, and Buffer deals with characters, so there is a conversion of bytes to characters and trust me it works well, there will not be any noticeable overhead.

So to Read the File:

File f = new File("Path");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);

So to Write the File:

File f = new File("Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);

And when you use Scanner there is no need to use BufferedReader