简体   繁体   中英

Why doesn't FileWriter in Java work often but sometimes does work?

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?

There are at least 2 significant things 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 immediately before the close() (or anywhere else) 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; eg D: could have a read-only file system mounted, or some anti-virus product could be interfering, or something like that.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM