1 package file; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.SequenceInputStream; 8 import java.util.Enumeration; 9 import java.util.Vector; 10 11 public class Demo9 { 12 public static void main(String[] args) throws IOException { 13 // merge1(); 14 merge2(); 15 } 16 17 18 //把三个文件合并 19 public static void merge2() throws IOException { 20 //找到目标文件 21 File inFile1 = new File("F:\1.txt"); 22 File inFile2 = new File("F:\2.txt"); 23 File inFile3 = new File("F:\3.txt"); 24 File outFile = new File("F:\a.txt"); 25 //建立数据的输入输出通道 26 FileOutputStream fileOutputStream = new FileOutputStream(outFile); 27 FileInputStream fileInputStream1 = new FileInputStream(inFile1); 28 FileInputStream fileInputStream2 = new FileInputStream(inFile2); 29 FileInputStream fileInputStream3 = new FileInputStream(inFile3); 30 31 //创建序列流对象 32 Vector<FileInputStream> vector = new Vector<FileInputStream>(); 33 vector.add(fileInputStream1); 34 vector.add(fileInputStream2); 35 vector.add(fileInputStream3); 36 Enumeration<FileInputStream> e = vector.elements(); 37 38 SequenceInputStream sequenceInputStream = new SequenceInputStream(e); 39 40 //读取文件数据 41 byte[] buf = new byte[1024]; 42 int length = 0; 43 while((length = sequenceInputStream.read(buf))!=-1) { 44 fileOutputStream.write(buf, 0, length); 45 } 46 sequenceInputStream.close(); 47 fileOutputStream.close(); 48 } 49 50 //使用SequenceInputStream合并 51 public static void merge1() throws IOException { 52 //找到目标文件 53 File inFile1 = new File("F:\2.txt"); 54 File inFile2 = new File("F:\a.txt"); 55 File outFile = new File("F:\1.txt"); 56 //建立数据的输入输出通道 57 FileOutputStream fileOutputStream = new FileOutputStream(outFile); 58 FileInputStream fileInputStream1 = new FileInputStream(inFile1); 59 FileInputStream fileInputStream2 = new FileInputStream(inFile2); 60 //建立序列流对象 61 SequenceInputStream inputStream = new SequenceInputStream(fileInputStream1,fileInputStream2); 62 byte[] buf = new byte[1024]; 63 int length = 0; 64 65 while((length = inputStream.read(buf))!=-1) { 66 fileOutputStream.write(buf, 0, length); 67 } 68 //关闭资源 69 inputStream.close(); 70 fileOutputStream.close(); 71 } 72 }