1 19 20 package org.netbeans.modules.java.source.engine; 21 22 import java.io.BufferedWriter ; 23 import java.io.File ; 24 import java.io.FileNotFoundException ; 25 import java.io.FileOutputStream ; 26 import java.io.FileWriter ; 27 import java.io.IOException ; 28 import java.io.OutputStreamWriter ; 29 import java.io.PrintWriter ; 30 import java.io.Writer ; 31 import javax.swing.text.BadLocationException ; 32 import javax.tools.JavaFileObject; 33 import org.openide.filesystems.FileObject; 34 import org.openide.filesystems.FileUtil; 35 36 39 public class FileSourceRewriter implements SourceRewriter { 40 JavaFileObject sourcefile; 41 PrintWriter out; 42 File outFile; 43 44 public FileSourceRewriter(JavaFileObject sourcefile) throws IOException { 45 this(sourcefile, null); 46 } 47 48 public FileSourceRewriter(JavaFileObject sourcefile, String encoding) throws IOException { 49 this.sourcefile = sourcefile; 50 String srcFile = sourcefile.toString(); 51 File f = new File (srcFile); 52 if (!f.exists()) 53 throw new FileNotFoundException (srcFile); 54 if (!f.canWrite()) 55 throw new IOException ("cannot write to " + srcFile); 56 57 outFile = new File (sourcefile.toUri().getPath() + ".tmp"); 58 Writer fileWriter = (encoding != null && encoding.length() > 0) ? 59 new OutputStreamWriter (new FileOutputStream (outFile), encoding) : 60 new FileWriter (outFile); 61 out = new PrintWriter (new BufferedWriter (fileWriter)); 62 } 63 64 public void writeTo(String s) throws IOException , BadLocationException { 65 out.print(s); 66 } 67 68 public void skipThrough(SourceReader in, int offset) throws IOException , BadLocationException { 69 in.seek(offset); 70 } 71 72 public void copyTo(SourceReader in, int offset) throws IOException { 73 char[] buf = in.getCharsTo(offset); 74 out.write(buf); 75 } 76 77 public void copyRest(SourceReader in) throws IOException { 78 char[] buf = new char[4096]; 79 int i; 80 while ((i = in.read(buf)) > 0) 81 out.write(buf, 0, i); 82 } 83 84 public void close(boolean save) throws IOException { 85 out.close(); 86 out = null; 87 if (save) { 88 String path = sourcefile.toUri().getPath(); 89 File f = new File (path); 90 File old = new File (path + '~'); 91 if (old.exists()) 92 if (!old.delete()) 93 throw new IOException ("failed deleting backup file: " + old); 94 if (!f.renameTo(old)) 95 throw new IOException ("failed renaming (" + path + 96 ") to backup (" + old + ")"); 97 f = new File (path); 98 if (!outFile.renameTo(f)) 99 throw new IOException ("failed renaming new output file (" + outFile + 100 ") to path (" + path + ")"); 101 outFile = f; 102 103 FileObject fo = FileUtil.toFileObject(outFile); 104 if (fo != null) { 105 fo.refresh(true); 106 } 107 } 108 } 109 } 110 | Popular Tags |