1 18 package net.sf.drftpd.util; 19 20 import java.io.File ; 21 import java.io.FileOutputStream ; 22 import java.io.IOException ; 23 import java.io.OutputStreamWriter ; 24 import java.io.Writer ; 25 26 import org.apache.log4j.Logger; 27 28 32 public class SafeFileWriter extends Writer { 33 private File _actualFile; 34 private OutputStreamWriter _out; 35 private File _tempFile; 36 private boolean failed = false; 37 38 41 public SafeFileWriter(File file) throws IOException { 42 _actualFile = file; 43 if (!_actualFile.getAbsoluteFile().getParentFile().canWrite()) 44 throw new IOException ("Can't write to target dir"); 45 46 File dir = _actualFile.getParentFile(); 47 if(dir == null) dir = new File ("."); 48 _tempFile = 49 File.createTempFile( 50 _actualFile.getName(), 51 null, 52 dir); 53 _out = new OutputStreamWriter (new FileOutputStream (_tempFile), "UTF-8"); 54 } 55 56 59 public SafeFileWriter(String fileName) throws IOException { 60 this(new File (fileName)); 61 } 62 63 public void close() throws IOException { 64 _out.flush(); 65 _out.close(); 66 if (!failed) { 67 Logger.getLogger(SafeFileWriter.class).debug("Renaming "+_tempFile+" ("+_tempFile.length()+") to "+_actualFile); 68 if (_actualFile.exists() && !_actualFile.delete()) 69 throw new IOException ("delete() failed"); 70 if (!_tempFile.exists()) 71 throw new IOException ("source doesn't exist"); 72 if (!_tempFile.renameTo(_actualFile)) 73 throw new IOException ( 74 "renameTo(" + _tempFile + ", " + _actualFile + ") failed"); 75 } 76 } 77 78 public void flush() throws IOException { 79 _out.flush(); 80 } 81 82 public void write(char[] cbuf, int off, int len) throws IOException { 83 try { 84 _out.write(cbuf, off, len); 85 } catch (IOException e) { 86 failed = true; 87 throw e; 88 } 89 } 90 } 91 | Popular Tags |