1 11 package org.eclipse.core.internal.runtime; 12 13 import java.io.*; 14 15 25 public class SafeFileOutputStream extends OutputStream { 26 protected File temp; 27 protected File target; 28 protected OutputStream output; 29 protected boolean failed; 30 protected static final String EXTENSION = ".bak"; 32 public SafeFileOutputStream(File file) throws IOException { 33 this(file.getAbsolutePath(), null); 34 } 35 36 public SafeFileOutputStream(String targetName) throws IOException { 37 this(targetName, null); 38 } 39 40 43 public SafeFileOutputStream(String targetPath, String tempPath) throws IOException { 44 failed = false; 45 target = new File(targetPath); 46 createTempFile(tempPath); 47 if (!target.exists() && !temp.exists()) { 51 output = new BufferedOutputStream(new FileOutputStream(target)); 52 return; 53 } 54 copy(temp, target); 55 output = new BufferedOutputStream(new FileOutputStream(temp)); 56 } 57 58 public void close() throws IOException { 59 close(false); 60 } 61 62 public void close(boolean discard) throws IOException { 63 try { 64 output.close(); 65 } catch (IOException e) { 66 failed = true; 67 throw e; } 69 if (discard || failed) 70 temp.delete(); 71 else 72 commit(); 73 } 74 75 protected void commit() throws IOException { 76 if (!temp.exists()) 77 return; 78 target.delete(); 79 copy(temp, target); 80 temp.delete(); 81 } 82 83 protected void copy(File sourceFile, File destinationFile) throws IOException { 84 if (!sourceFile.exists()) 85 return; 86 if (sourceFile.renameTo(destinationFile)) 87 return; 88 InputStream source = new BufferedInputStream(new FileInputStream(sourceFile)); 89 OutputStream destination = new BufferedOutputStream(new FileOutputStream(destinationFile)); 90 transferStreams(source, destination); 91 } 92 93 protected void createTempFile(String tempPath) { 94 if (tempPath == null) 95 tempPath = target.getAbsolutePath() + EXTENSION; 96 temp = new File(tempPath); 97 } 98 99 public void flush() throws IOException { 100 try { 101 output.flush(); 102 } catch (IOException e) { 103 failed = true; 104 throw e; } 106 } 107 108 public String getTempFilePath() { 109 return temp.getAbsolutePath(); 110 } 111 112 protected void transferStreams(InputStream source, OutputStream destination) throws IOException { 113 try { 114 byte[] buffer = new byte[8192]; 115 while (true) { 116 int bytesRead = source.read(buffer); 117 if (bytesRead == -1) 118 break; 119 destination.write(buffer, 0, bytesRead); 120 } 121 } finally { 122 try { 123 source.close(); 124 } catch (IOException e) { 125 } 127 try { 128 destination.close(); 129 } catch (IOException e) { 130 } 132 } 133 } 134 135 public void write(int b) throws IOException { 136 try { 137 output.write(b); 138 } catch (IOException e) { 139 failed = true; 140 throw e; } 142 } 143 } | Popular Tags |