public class StagedWrite
extends java.lang.Object
implements java.io.Closeable
Helper to do staged file writes. In a staged write, code first writes the output to a temporary file, then renames the temporary file on top of the target file. To use this file:
try (StagedWrite stage = StagedWrite.begin(outputFile)) {
try (OutputStream stream = stage.openOutputStream()) {
// write to stream
}
stage.commit();
}
The rename operation is atomic, so outside code will either see the old target file (or lack thereof), or the entire contents of the new target file; it will not see any intermediate states. It is possible that this code will fail on old versions of Windows, or on certain file systems; if you encounter problems with it, especially if it raises AtomicMoveNotSupportedException
, please file a bug report.
Modifier and Type | Method and Description |
---|---|
static StagedWrite |
begin(java.io.File target)
Begin a staged file writing operation.
|
static StagedWrite |
begin(java.nio.file.Path target)
Begin a staged file writing operation.
|
void |
close()
Clean up the staged write, deleting the staging file if it still exists.
|
void |
commit()
Complete the staging write by replacing the target file with the staging file.
|
java.nio.file.Path |
getStagingFile()
Get the working file for this staging file.
|
java.nio.file.Path |
getTargetFile()
Get the target file for this staging file.
|
java.io.OutputStream |
openOutputStream()
Open an output stream for the staging file.
|
public static StagedWrite begin(java.nio.file.Path target)
Begin a staged file writing operation.
target
- The file to write.public static StagedWrite begin(java.io.File target)
Begin a staged file writing operation.
target
- The file to write.public java.nio.file.Path getTargetFile()
Get the target file for this staging file.
public java.nio.file.Path getStagingFile()
Get the working file for this staging file. Code doing staged file writes should write to this file.
public java.io.OutputStream openOutputStream() throws java.io.IOException
Open an output stream for the staging file. This method cannot be called multiple times.
commit()
.java.io.IOException
- if there is an error opening the output stream.public void commit() throws java.io.IOException
Complete the staging write by replacing the target file with the staging file. Any streams or channels used to write the file must be closed and/or flushed prior to calling this method.
java.io.IOException
- if there is an error moving the file.public void close() throws java.io.IOException
Clean up the staged write, deleting the staging file if it still exists. It is safe to call this method multiple times, and safe to call it after calling commit()
. Typical use of a staged write will call this method in a finally
block, or use the staged write in a try-with-resources block.
close
in interface java.io.Closeable
close
in interface java.lang.AutoCloseable
java.io.IOException