1

I am making a simple program that put data into a file using FileWriter.

But I am facing a problem. My code is creating the fie but not putting data into the file.

import java.io.*;

class Temp
{
    public static void main(String args[])throws Exception
    {
        FileWriter fw=new FileWriter("ma.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        String str="dslkm dsk";
        bw.write(str);
    }
}

Why is this happening?

3 Answers 3

2

You need to flush and close the writer.

bw.flush();
bw.close();

Even just closing the writer should be enough, since it automatically flushes before closing.

Sign up to request clarification or add additional context in comments.

Comments

0

Your code should be:

    public static void main(String args[])throws Exception
    {
        FileWriter fw=new FileWriter("ma.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        String str="dslkm dsk";
        bw.write(str);
        bw.flush();
        bw.close();
    }

1 Comment

oh, I have seen two responses just now. I am little bit late without refreshing the question.
0

A file writer always need to be closed or flushed. Otherwise there is no guarantee to the write the bytes/characters in it to be written in your file.And it's better to use fileWriter with try-catch-finally block -

try {
       FileWriter fw=new FileWriter("ma.txt");
       BufferedWriter bw=new BufferedWriter(fw);
       String str="dslkm dsk";
       bw.write(str);

    } catch (IOException ex){
       System.err.println("Couldn't log this: "+s);
    }finally{
       bw.close();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.