KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > util > AtomicFileWriter


1 package hudson.util;
2
3 import java.io.BufferedWriter JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileOutputStream JavaDoc;
6 import java.io.FileWriter JavaDoc;
7 import java.io.IOException JavaDoc;
8 import java.io.OutputStreamWriter JavaDoc;
9 import java.io.Writer JavaDoc;
10
11 /**
12  * Buffered {@link FileWriter} that uses UTF-8.
13  *
14  * <p>
15  * The write operation is atomic when used for overwriting;
16  * it either leaves the original file intact, or it completely rewrites it with new contents.
17  *
18  * @author Kohsuke Kawaguchi
19  */

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