Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement