1 19 package org.netbeans.lib.cvsclient.file; 20 21 import java.io.*; 22 23 27 public class DefaultTransmitTextFilePreprocessor 28 implements TransmitTextFilePreprocessor { 29 30 private static final int CHUNK_SIZE = 32768; 31 32 private File tempDir; 33 34 public void setTempDir(File tempDir) { 35 this.tempDir = tempDir; 36 } 37 38 public File getPreprocessedTextFile(File originalTextFile) throws IOException { 39 File preprocessedTextFile = File.createTempFile("cvs", null, tempDir); 43 byte[] newLine = System.getProperty("line.separator").getBytes(); 44 boolean doConversion = newLine.length != 1 || newLine[0] != '\n'; 45 46 OutputStream out = null; 47 InputStream in = null; 48 49 try { 50 in = new BufferedInputStream(new FileInputStream(originalTextFile)); 51 out = new BufferedOutputStream(new FileOutputStream(preprocessedTextFile)); 52 53 byte[] fileChunk = new byte[CHUNK_SIZE]; 54 byte[] fileWriteChunk = new byte[CHUNK_SIZE]; 55 56 for (int readLength = in.read(fileChunk); 57 readLength > 0; 58 readLength = in.read(fileChunk)) { 59 60 if (doConversion) { 61 int writeLength = 0; 62 for (int i = 0; i < readLength; ) { 63 int pos = findIndexOf(fileChunk, newLine, i); 64 if (pos >= i && pos < readLength) { 65 System.arraycopy(fileChunk, i, fileWriteChunk, writeLength, pos - i); 66 writeLength += pos - i; 67 i = pos + newLine.length; 68 fileWriteChunk[writeLength++] = '\n'; 69 } else { 70 System.arraycopy(fileChunk, i, fileWriteChunk, writeLength, readLength - i); 71 writeLength += readLength - i; 72 i = readLength; 73 } 74 } 75 out.write(fileWriteChunk, 0, writeLength); 76 } else { 77 out.write(fileChunk, 0, readLength); 78 } 79 } 80 return preprocessedTextFile; 81 } 82 catch (IOException ex) { 83 if (preprocessedTextFile != null) { 84 cleanup(preprocessedTextFile); 85 } 86 throw ex; 87 } 88 finally { 89 if (in != null) { 90 try { 91 in.close(); 92 } 93 catch (IOException ex) { 94 } 96 } 97 if (out != null) { 98 try { 99 out.close(); 100 } 101 catch (IOException ex) { 102 } 104 } 105 } 106 } 107 108 private static int findIndexOf(byte[] array, byte[] pattern, int start) { 109 int subPosition = 0; 110 for (int i = start; i < array.length; i++) { 111 if (array[i] == pattern[subPosition]) { 112 if (++subPosition == pattern.length) { 113 return i - subPosition + 1; 114 } 115 } else { 116 subPosition = 0; 117 } 118 } 119 return -1; 120 } 121 122 public void cleanup(File preprocessedTextFile) { 123 if (preprocessedTextFile != null) { 124 preprocessedTextFile.delete(); 125 } 126 } 127 128 } 129 | Popular Tags |