java入门 -- 使用序列流SequenceInputStream合并文件

/* * 序列流: * SequenceInputStream * 

 * 小程序:使用序列流合并文件内容 */

package com.michael.lin;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.SequenceInputStream;

import java.util.Enumeration;

import java.util.Vector;

public class Demo01 {

public static void main(String[] args) throws IOException{

merge();

merge3();

}

//合并三个文件

public static void merge3() throws IOException{

//1.定位文件

File file1 = new File("c:\\a.txt");

File file2 = new File("c:\\buf.txt");

File file3 = new File("c:\\data.txt");

File outFile = new File("c:\\outFile.txt");

//2.构建文件输入输出通道

FileInputStream fileInputStream1 = new FileInputStream(file1);

FileInputStream fileInputStream2 = new FileInputStream(file2);

FileInputStream fileInputStream3 = new FileInputStream(file3);

FileOutputStream fileOutputStream = new FileOutputStream(outFile);

//3.将输入序列接入到序列流中

Vectorvector = new Vector();

vector.add(fileInputStream1);

vector.add(fileInputStream2);

vector.add(fileInputStream3);

Enumerationenumeration = vector.elements();

SequenceInputStream seqInputStrem = new SequenceInputStream(enumeration);

//4.读取序列流中的内容并输出

int length = 0;

byte[] buf = new byte[1024];

while((length=seqInputStrem.read(buf))!=-1){

fileOutputStream.write(buf,0,length);

}

//5.关闭资源

seqInputStrem.close();

fileOutputStream.close();

}

//使用序列流和SequenceInputStreanm合并两个文件

public static void merge() throws IOException{

//1.定位文件

File file1 = new File("c:\\buf.txt");

File file2 = new File("c:\\data.txt");

File outFile = new File("c:\\bufData.txt");

//2.构建输入输出通道

FileInputStream fileInputStrem1 = new FileInputStream(file1);

FileInputStream fileInputStram2 = new FileInputStream(file2);

FileOutputStream fileOutputStream = new FileOutputStream(outFile);

//3.将输入通道介入到序列流中

SequenceInputStream seqInputStream = new SequenceInputStream(fileInputStrem1,fileInputStram2);

//4.从序列流中读取数据放入输出流中

int length = 0;

byte[] buf = new byte[1024];

while((length=seqInputStream.read(buf))!=-1){

fileOutputStream.write(buf,0,length);

}

//5.关闭通道

seqInputStream.close();

fileOutputStream.close();

}

}

你可能感兴趣的:(java入门 -- 使用序列流SequenceInputStream合并文件)