public class StagedWrite extends Object implements 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(File target)
Begin a staged file writing operation.
|
static StagedWrite |
begin(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.
|
Path |
getStagingFile()
Get the working file for this staging file.
|
Path |
getTargetFile()
Get the target file for this staging file.
|
OutputStream |
openOutputStream()
Open an output stream for the staging file.
|
public static StagedWrite begin(Path target)
Begin a staged file writing operation.
target
- The file to write.public static StagedWrite begin(File target)
Begin a staged file writing operation.
target
- The file to write.public Path getTargetFile()
Get the target file for this staging file.
public Path getStagingFile()
Get the working file for this staging file. Code doing staged file writes should write to this file.
public OutputStream openOutputStream() throws IOException
Open an output stream for the staging file. This method cannot be called multiple times.
commit()
.IOException
- if there is an error opening the output stream.public void commit() throws 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.
IOException
- if there is an error moving the file.public void close() throws 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 Closeable
close
in interface AutoCloseable
IOException