brain storm
brain storm

Reputation: 31272

why filewriter not working in java?

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

Answers (3)

Adnan
Adnan

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

NFE
NFE

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

ced-b
ced-b

Reputation: 4065

You need to call out.flush() when you are done.

Upvotes: 1

Related Questions