When does BufferedWriter create file?

Using BufferedWriter.write() when is a file created?

I know from the docs that when the buffer is filled it will flush to file, does this mean that:

every-time the buffer is filled an incomplete file will appear on my file system?

or that the file is only created when the BufferedWriter is closed?

My concern is that I am writing files to a directory using a BufferedWriter and another process is polling the directory for new files and reading them. I do not want an incomplete file to be created and be read by the other process.

Jon Skeet
people
quotationmark

Using BufferedWriter.write() when is a file created?

Never. BufferedWriter itself just writes to another Writer. Now if you're using a FileOutputStream or a FileWriter (where the first would probably be wrapped in an OutputStreamWriter) the file is created (or opened for write if it already exists) when you construct the object, i.e. before you've actually written any data.

My concern is that I am writing files to a directory using a BufferedWriter and another process is polling the directory for new files and reading them. I do not want an incomplete file to be created and be read by the other process.

One typical way of handling this is to write to a staging area and then rename the file into the correct place, which is usually an atomic operation. Or even write the file into the correct directory, but with a file extension which the polling process won't spot - and then rename the file to the final filename afterwards.

people

See more on this question at Stackoverflow