切割可以分两种方式:按文件个数切,按文件大小来切(建议用这种方式,因为按个数的话,有可能文件非常大)
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 6 public class SplitFileDemo { 7 private static final int SIZE = 1024*1024;//1M=1024*1024个字节 8 9 public static void main(String[] args) throws IOException { 10 File file = new File("F:\jian.avi"); 11 splitFileDemo(file); 12 13 } 14 public static void splitFileDemo(File file) throws IOException { 15 16 //用读取流关联一个文件 17 FileInputStream fis = new FileInputStream(file); 18 //定义一个1M的缓冲区 19 byte[] buf = new byte[SIZE]; 20 21 //创建目的 22 FileOutputStream fos = null; 23 24 File dir = new File("F:\partfiles"); 25 26 if(!dir.exists()){ 27 dir.mkdirs(); 28 } 29 30 int count = 1; 31 int len = 0; 32 while((len = fis.read(buf))!=-1){ 33 fos = new FileOutputStream(new File(dir,(count++)+".part"));//扩展名可以依据软件的需求来定义,但不要是txt这些扩展名,因为切割完的文件不能直接读取 34 fos.write(buf,0,len); 35 } 36 fos.close(); 37 fis.close(); 38 } 39 }
合并:
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.SequenceInputStream; 6 import java.util.ArrayList; 7 import java.util.Collections; 8 import java.util.Enumeration; 9 import java.util.Properties; 10 11 public class MergeFile { 12 public static void main(String[] args) throws IOException { 13 14 File dir = new File("c:\partfiles"); 15 16 mergeFile(dir); 17 } 18 public static void mergeFile(File dir) throws IOException{ 19 20 21 ArrayList<FileInputStream> al = new ArrayList<FileInputStream>(); 22 23 for(int x=1; x<=3 ;x++){ 24 al.add(new FileInputStream(new File(dir,x+".part"))); 25 } 26 27 Enumeration<FileInputStream> en = Collections.enumeration(al); 28 SequenceInputStream sis = new SequenceInputStream(en); 29 30 FileOutputStream fos = new FileOutputStream(new File(dir,"1.bmp")); 31 32 byte[] buf = new byte[1024]; 33 34 int len = 0; 35 while((len=sis.read(buf))!=-1){ 36 fos.write(buf,0,len); 37 } 38 39 fos.close(); 40 sis.close(); 41 42 } 43 44 }