1 package hudson.util; 2 3 import java.io.BufferedWriter ; 4 import java.io.File ; 5 import java.io.FileOutputStream ; 6 import java.io.FileWriter ; 7 import java.io.IOException ; 8 import java.io.OutputStreamWriter ; 9 import java.io.Writer ; 10 11 20 public class AtomicFileWriter extends Writer { 21 22 private final Writer core; 23 private final File tmpFile; 24 private final File destFile; 25 26 public AtomicFileWriter(File f) throws IOException { 27 tmpFile = File.createTempFile("atomic",null,f.getParentFile()); 28 destFile = f; 29 core = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (tmpFile),"UTF-8")); 30 } 31 32 public void write(int c) throws IOException { 33 core.write(c); 34 } 35 36 public void write(String str, int off, int len) throws IOException { 37 core.write(str,off,len); 38 } 39 40 public void write(char cbuf[], int off, int len) throws IOException { 41 core.write(cbuf,off,len); 42 } 43 44 public void flush() throws IOException { 45 core.flush(); 46 } 47 48 public void close() throws IOException { 49 core.close(); 50 } 51 52 public void commit() throws IOException { 53 close(); 54 if(destFile.exists() && !destFile.delete()) 55 throw new IOException ("Unable to delete "+destFile); 56 tmpFile.renameTo(destFile); 57 } 58 } 59 | Popular Tags |