Reputation: 31272
I using FileReader
to read and FileWriter
to a file. I am seeing that reading is successful (by printing to console
) but writing does not happen.
here is the code:
public class ReadingIO {
public static void main(String[] args){
try {
processfile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void processfile() throws IOException{
BufferedReader fi = new BufferedReader(new FileReader("words.txt"));
Writer out = new BufferedWriter(new FileWriter("testwrite.txt"));
String b;
while ((b=fi.readLine())!=null){
System.out.println(b);
out.write(b);
}
}
}
If I use FileInputStream
and FileOutputStream
it works. I want to know why FileWriter fails, not alternative ways to accomplish this.
Upvotes: 0
Views: 767
Reputation: 5085
Add following lines after while loop.
out.close();
This method will cal flush() method automatically to write data to file which is still buffered, then close the stream.
Upvotes: 1
Reputation: 1187
You need to call flush() while using Writer
.
But not needed while FileOutputStream
Close calls flush on the stream, so flush is not needed if you want to close the stream.
Upvotes: 2