Advertisement
Guest User

Untitled

a guest
May 24th, 2015
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6.  
  7. /**
  8. * FailSafeFile guarantees that the complete file is written before renaming it
  9. * to its actual name. Everything is written to a .tmp hidden file unless
  10. * finishWrite() is called.
  11. */
  12. public class FailSafeFile {
  13.  
  14. private final File mBaseFile;
  15.  
  16. private final File mTempFile;
  17.  
  18. public FailSafeFile(File baseFile) {
  19. mBaseFile = baseFile;
  20. mTempFile = new File(baseFile.getParent(), "." + baseFile.getName() + ".tmp");
  21. }
  22.  
  23. public File getBaseFile() {
  24. return mBaseFile;
  25. }
  26.  
  27. public void delete() {
  28. mBaseFile.delete();
  29. mTempFile.delete();
  30. }
  31.  
  32. public FileInputStream openRead() throws FileNotFoundException {
  33. mTempFile.delete();
  34. return new FileInputStream(mBaseFile);
  35. }
  36.  
  37. public FileOutputStream startWrite() throws FileNotFoundException {
  38. delete();
  39. mTempFile.getParentFile().mkdirs();
  40. return new FileOutputStream(mTempFile);
  41. }
  42.  
  43. public boolean finishWrite(FileOutputStream str) throws IOException {
  44. str.getFD().sync();
  45. str.close();
  46. return mTempFile.renameTo(mBaseFile);
  47. }
  48.  
  49. public void failWrite(FileOutputStream str) throws IOException {
  50. str.getFD().sync();
  51. str.close();
  52. delete();
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement