Skip to content

Instantly share code, notes, and snippets.

@gitanuj
Created April 13, 2015 18:33
Show Gist options
  • Save gitanuj/996ec7ca69a8a60ccea3 to your computer and use it in GitHub Desktop.
Save gitanuj/996ec7ca69a8a60ccea3 to your computer and use it in GitHub Desktop.
FailSafeFile for Java. Ensures that only complete file is written to the disk.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* FailSafeFile guarantees that the complete file is written before renaming it
* to its actual name. Everything is written to a .tmp hidden file unless
* finishWrite() is called.
*/
public class FailSafeFile {
private final File mBaseFile;
private final File mTempFile;
public FailSafeFile(File baseFile) {
mBaseFile = baseFile;
mTempFile = new File(baseFile.getParent(), "." + baseFile.getName() + ".tmp");
}
public File getBaseFile() {
return mBaseFile;
}
public void delete() {
mBaseFile.delete();
mTempFile.delete();
}
public FileInputStream openRead() throws FileNotFoundException {
mTempFile.delete();
return new FileInputStream(mBaseFile);
}
public FileOutputStream startWrite() throws FileNotFoundException {
delete();
mTempFile.getParentFile().mkdirs();
return new FileOutputStream(mTempFile);
}
public boolean finishWrite(FileOutputStream str) throws IOException {
str.getFD().sync();
str.close();
return mTempFile.renameTo(mBaseFile);
}
public void failWrite(FileOutputStream str) throws IOException {
str.getFD().sync();
str.close();
delete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment