1 12 package org.eclipse.jdt.apt.core.internal.env; 13 14 import java.io.BufferedInputStream ; 15 import java.io.ByteArrayInputStream ; 16 import java.io.ByteArrayOutputStream ; 17 import java.io.IOException ; 18 import java.io.InputStream ; 19 import java.util.Collections ; 20 21 import org.eclipse.core.resources.IFile; 22 import org.eclipse.core.runtime.CoreException; 23 import org.eclipse.jdt.apt.core.internal.AptPlugin; 24 import org.eclipse.jdt.apt.core.internal.util.FileSystemUtil; 25 26 31 public class BinaryFileOutputStream extends ByteArrayOutputStream { 32 33 protected final IFile _file; 34 private final BuildEnv _env; 35 36 public BinaryFileOutputStream(IFile file, BuildEnv env) { 37 _file = file; 38 _env = env; 39 } 40 41 @Override 42 public void close() throws IOException { 43 super.close(); 44 45 InputStream contents = new ByteArrayInputStream (toByteArray()); 46 try { 47 48 boolean contentsChanged = true; 49 if (!_file.exists()) { 50 saveToDisk(contents, true); 51 } 52 else { 53 InputStream in = null; 54 InputStream oldData = null; 55 try { 56 in = new ByteArrayInputStream (toByteArray()); 58 oldData = new BufferedInputStream (_file.getContents()); 59 if (FileSystemUtil.compareStreams(in, oldData)) { 60 contentsChanged = false; 61 } 62 } 63 catch (CoreException ce) { 64 contentsChanged = true; 66 } 67 finally { 68 closeInputStream(in); 69 closeInputStream(oldData); 70 } 71 if (contentsChanged) { 72 contents.reset(); 73 saveToDisk(contents, false); 74 } 75 } 76 } 77 finally { 78 closeInputStream(contents); 79 } 80 81 IFile parentFile = _env.getFile(); 82 if (parentFile != null) { 83 _env.getAptProject().getGeneratedFileManager().addGeneratedFileDependency(Collections.singleton(parentFile), _file); 84 _env.addGeneratedNonSourceFile(_file); 85 } 86 } 87 88 private void closeInputStream(InputStream stream) { 89 if (stream != null) { 90 try { 91 stream.close(); 92 } 93 catch (IOException ioe) {} 94 } 95 } 96 97 private void saveToDisk(InputStream toSave, boolean create) throws IOException { 98 try { 99 FileSystemUtil.makeDerivedParentFolders(_file.getParent()); 100 if (create) { 101 _file.create(toSave, true, null); 102 _file.setDerived(true); 103 } 104 else { 105 _file.setContents(toSave, true, false, null); 106 } 107 } 108 catch (CoreException ce) { 109 if (_file.exists()) { 110 } 113 else { 114 AptPlugin.log(ce, "Could not create generated file"); throw new IOException (ce.getMessage()); 116 } 117 } 118 } 119 120 } 121 | Popular Tags |