1 6 7 package SOFA.SOFAnet.Transport; 8 9 import java.io.*; 10 import java.util.*; 11 import SOFA.Util.Tools; 12 14 23 public class BundleData 24 { 25 private File tempFile; 26 27 35 public BundleData(File sourceFile, boolean copy) 36 { 37 if (copy) 38 { 39 tempFile = new File(generateFilename()); 40 41 try 42 { 43 FileInputStream in = new FileInputStream(sourceFile); 44 FileOutputStream out = new FileOutputStream(tempFile); 45 Tools.copyStream(in, out); 46 in.close(); 47 out.close(); 48 } 49 catch (FileNotFoundException e) 50 { 51 delete(); 52 } 53 catch (IOException e) 54 { 55 delete(); 56 } 57 } 58 else 59 { 60 this.tempFile = sourceFile; 61 } 62 } 63 64 70 public BundleData(byte[] data) 71 { 72 if (data == null) 73 { 74 delete(); 75 return; 76 } 77 78 tempFile = new File(generateFilename()); 79 80 try 81 { 82 ByteArrayInputStream in = new ByteArrayInputStream(data); 83 FileOutputStream out = new FileOutputStream(tempFile); 84 Tools.copyStream(in, out); 85 in.close(); 86 out.close(); 87 } 88 catch (FileNotFoundException e) 89 { 90 delete(); 91 } 92 catch (IOException e) 93 { 94 delete(); 95 } 96 } 97 98 99 public void delete() 100 { 101 if (tempFile != null) 102 { 103 tempFile.delete(); 104 tempFile = null; 105 } 106 } 107 108 109 public void release() 110 { 111 tempFile = null; 112 } 113 114 115 public File getFile() 116 { 117 return tempFile; 118 } 119 120 124 public byte[] getData() 125 { 126 if (tempFile == null) return null; 127 128 try 129 { 130 FileInputStream is = new FileInputStream(tempFile); 131 ByteArrayOutputStream os = new ByteArrayOutputStream(); 132 Tools.copyStream(is, os); 133 is.close(); 134 byte[] result = os.toByteArray(); 135 os.close(); 136 return result; 137 } 138 catch (FileNotFoundException e) 139 { 140 return null; 141 } 142 catch (IOException e) 143 { 144 return null; 145 } 146 } 147 148 154 public boolean copyToFile(File destFile, boolean deleteOnError) 155 { 156 if (destFile == null) return false; 157 if (tempFile == null) 158 { 159 if (deleteOnError) destFile.delete(); 160 return false; 161 } 162 163 try 164 { 165 FileInputStream in = new FileInputStream(tempFile); 166 FileOutputStream out = new FileOutputStream(destFile); 167 Tools.copyStream(in, out); 168 in.close(); 169 out.close(); 170 } 171 catch (FileNotFoundException e) 172 { 173 if (deleteOnError) destFile.delete(); 174 return false; 175 } 176 catch (IOException e) 177 { 178 if (deleteOnError) destFile.delete(); 179 return false; 180 } 181 182 return true; 183 } 184 185 186 protected void finalize () throws Throwable 187 { 188 delete(); 189 super.finalize(); 190 } 191 192 193 public static String generateFilename() 194 { 195 return System.getProperty("java.io.tmpdir") + File.separator + "sofabundle" + Long.toString(new Date().getTime()) + ".jar"; 196 } 197 } 198 | Popular Tags |