Home > Software design >  Why doesn't FileWriter in Java work often but sometimes does work?
Why doesn't FileWriter in Java work often but sometimes does work?

Time:11-28

public static void main( String[] args )
{
    try{
        String content = "hello";
        File file =new File("d:\\test_appendfile.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fileWritter = new FileWriter(file.getName(),true);
        fileWritter.write(content);
        fileWritter.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

Often, like 90% of possibility, there is nothing in "test_appendfile.txt". However, sometimes, content is successfully written in "test_appendfile.txt". Why?

CodePudding user response:

OK so there are at least 2 things that are wrong with your code ... and some others that are "suboptimal".

Problem #1

As @Preston points out, file.getName() is incorrect. In your example, it will return "test_appendfile.txt" which is different to pathname that you started with.

Does it make a difference? Well, it depends on what the JVM's working directory is! If it is "D://" then you are OK. Otherwise you will be writing a file in the current directory and not "D://" which could explain why the file in "D:// is empty.

You should use file as the constructor argument.

Problem #2

The close() call won't happen if an exception is thrown earlier in the try block. If the close() call doesn't happen, FileWriter buffer won't necessarily be flushed, and you could lose output.

You should use try with resources so that the FileWriter is always closed.

Calling flush() explicitly is a non-solution. An earlier exception would cause that to be skipped too.

Suboptimal code

This is unnecessary:

        if (!file.exists()) {
            file.createNewFile();
        }

The file will be created by new FileWriter(file, true); if it doesn't exist already. So the above doesn't achieve anything.

Some other possible explanations

You haven't shown us the import statements for your program so it is possible that File or FileWriter are not the standard classes.

It is possible that "something else" is preventing the writes; e.g. D: could have a read-only file system mounted, or some anti-virus product could be interfering, or something like that.

CodePudding user response:

You had given the wrong argument to the FileWriter constructor.
Just change the
FileWriter fileWritter = new FileWriter(file.getName(),true);
to
FileWriter fileWritter = new FileWriter(file,true);

  • Related