import java.io.FileInputStream; import java.io.FileOutputStream; /** This class chops up a file */ public class Chunk { public static void main(String[] s) throws Exception { if (s.length != 3) { System.err.println("Args are "); return; } int chunkSize; try { chunkSize = Integer.parseInt(s[2].trim()); } catch (NumberFormatException nfe) { System.err.println("Could not read chunk size in " + s[0]); return; } FileInputStream in = null; FileOutputStream out = null; byte[] buffer = new byte[1024 * 64]; try { in = new FileInputStream(s[0]); int writtenOut = 0; int inBuffer = 0; int inBufferOffset = 0; int outputFileCount = 1; for (;;) { if (inBuffer > inBufferOffset) { if (out == null) { out = new FileOutputStream(s[1] + (outputFileCount++)); writtenOut = 0; } int todo = inBuffer - inBufferOffset; if (todo > (chunkSize - writtenOut)) { todo = chunkSize - writtenOut; } if (todo <= 0) { out.close(); out = null; writtenOut = 0; continue; } out.write(buffer, inBufferOffset, todo); writtenOut += todo; inBufferOffset += todo; continue; } // Here with nothing else to write out inBuffer = in.read(buffer); if (inBuffer <= 0) { // end of file break; } inBufferOffset = 0; } } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.err.println("Exception closing input file " + ex); } } if (out != null) { try { out.close(); } catch (Exception ex) { System.err.println("Exception closing output file " + ex); } } } } }