Start Search Contents Index Links About
CopyFilePart.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Copy utility to copy only on sub section of the source
 * file to a new destination file.
 
 @author Havard Rast Blok
 *
 */
public class CopyFilePart {
  
  private File src;
  
  private File dest;
  
  public CopyFilePart(File src, File dest) {
    this.src = src;
    this.dest = dest;
    
    if(!src.exists() || !src.canRead() || !src.isFile()) {
      throw new IllegalArgumentException("Could not access or read file "+src);
    }
    
    if(dest.exists()) {
      throw new IllegalArgumentException("Destination file already exists: "+dest);
    }
  }
  
  /**
   * Copy the specified file of this class to the specifed destination.
   
   @throws IOException if any open, create, read or write error occurs.
   */
  public void copy(int start, int lengththrows IOException {
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
    
    in.skip(start);
    int i = 0;
    int b;
    while( (b = in.read()) != -&& i < length) {
      out.write(b);
      i++;
    }
    
    in.close();
    out.close();
  }
  
  /**
   * This utility takes two arguments, destination and host:
   * java CopyFilePart <source file> <destination file> <start> <length>
   
   */
  public static void main(String[] args) {
    if(args == null || args.length != 4) {
      System.out.println("Usage: java CopyFile <source file> <destination file> <start> <length>");
      System.exit(1);
    }
    
    CopyFilePart cp = new CopyFilePart(new File(args[0])new File(args[1]));
    try {
      cp.copy(Integer.parseInt(args[2]), Integer.parseInt(args[3]));
    catch (IOException e) {
      System.out.println("An error occured while coping the file: ");
      e.printStackTrace();
      System.exit(1);
    }
  }
  
  

}


site: Håvard Rast Blok
mail:
updated: 27 July 2007