自己写的文件分割的程序

来源:互联网 发布:ubuntu系统kvm网络配置 编辑:程序博客网 时间:2024/05/02 02:40

终于买了个闪存,128M的,中关村买的,花了120嘿嘿,

tmd,最近真穷,考虑到遇到大文件的问题,到网上下了个文件分割的软件,竟然要注册,什么玩艺啊,算了,还是自己写的好用

先发上了,谁看了有什么意见可以提提,本人比较懒,就没写文件合成的,只是生成了一个批处理,unix下是不能用这个批处理了,呵呵

import java.io.*;
import java.util.*;

public class FileSplit{

 protected int size;  //size of every sub file
 protected String fName; //
 protected Vector vNames = new Vector();

 protected static final String BatName = "resume.bat";
 
 public FileSplit(String fName){
  this.fName = fName;
  this.size = 1024*1024; //default size 1M
 }

 public FileSplit(String fName, int size){
  this.fName = fName;
  this.size = size*1024*1024; 
 }

 public File getFile(){
  File f = new File(fName);
  if(!f.exists()){
   f = null;
  }
  return f;
 }

 public String getName(){
  return fName;
 }

 public int getSize(){
  return size;
 }

 public void splitFile() throws Exception{
  System.out.println("Spliting files...");
  FileInputStream in = new FileInputStream(getFile());
  byte[] buf = new byte[getSize()];
  int i = 0;
  int ret;
  while((ret = in.read(buf)) != -1){
   //System.out.println(ret + " bytes read");
   save(fName+new Integer(i).toString(), buf, ret);
   i++;
  }
 }
 
 public void createBatFile(){
  String fName = "";
  if(getFile().getParent() != null){
   fName = getFile().getParent();
  }
  fName += BatName;
  String files = "";
  for(Enumeration e = vNames.elements(); e.hasMoreElements(); ){
   files += (String)e.nextElement();
   if(e.hasMoreElements()){
    files += " + ";
   }
  }
  try{
   FileOutputStream out = new FileOutputStream(new File(fName));
   out.write("echo off/r/n".getBytes());
   out.write("copy /B ".getBytes());
   out.write(files.getBytes());
   out.write((" "+getName()).getBytes());
   out.write("/r/n".getBytes());
   out.write("del ".getBytes());
   out.write(files.getBytes());
   out.write("/r/n".getBytes());
   out.write(("del " + BatName).getBytes());
   out.flush();
   out.close();
  }catch(Exception ex){
   System.err.println("Unable to create bat file!");
  }
 }

 private void addFileName(String fName){
  vNames.addElement(fName);
 }

 private Vector getNames(){
  return vNames;
 }

 private void save(String fName, byte[] buf, int len) throws Exception{
  File f = new File(fName);
  FileOutputStream out =new FileOutputStream(f);
  out.write(buf, 0, len);
  out.flush();
  out.close();
  addFileName(f.getName());
  System.out.println("File " + fName + " written.");
 }

 public static void main(String[] args){
  FileSplit split = null;
  if(args.length == 1){
   split = new FileSplit(args[0]);
  }
  else if(args.length == 2){
   split = new FileSplit(args[0], Integer.parseInt(args[1]));
  }
  else{
   System.err.println("need parameters: filename size(must be larger than 1M,default 1M)");
   System.exit(1);
  }
  try{
   split.splitFile();
  }
  catch(Exception ex){
   ex.printStackTrace();
   System.exit(1);
  }
  split.createBatFile();
 }

}