您的位置:首页 > 编程语言 > Java开发

Java IO流 合并流和切割流

2015-06-28 00:30 507 查看

合并流SequenceInputStream

多个文件输入流合并,初始化传入的参数必须是Enumeration<FileInputStream>类型的变量

package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

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

Vector<FileInputStream> v = new Vector<FileInputStream>();

v.add(new FileInputStream("E:\\1.txt"));
v.add(new FileInputStream("E:\\2.txt"));
v.add(new FileInputStream("E:\\3.txt"));

Enumeration<FileInputStream> en = v.elements();

//多个输入流放在Vector里, 第二个参数必须是Enumeration<FileInputStream>类型的变量
SequenceInputStream sis = new SequenceInputStream(en);

FileOutputStream fos = new FileOutputStream("E:\\4.txt");

byte[] buf = new byte[1024];

int len = 0;
while ((len = sis.read(buf)) != -1) {
fos.write(buf, 0, len);
}

fos.close();
sis.close();

}
}

切割流

读取文件时内容分多个文件保存,就造成切割的效果

package test;

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

class Test {

public static void main(String[] args) throws IOException {
splitFile(); //读取文件时内容分多个文件保存,就造成切割的效果
//merge();    //合并流合并切割出来的几个文件
}

public static void merge() throws IOException {
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();

for (int x = 1; x <= 3; x++) {
al.add(new FileInputStream("c:\\splitfiles\\" + x + ".part"));
}

final Iterator<FileInputStream> it = al.iterator();

Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
public boolean hasMoreElements() {
return it.hasNext();
}

public FileInputStream nextElement() {
return it.next();
}
};

SequenceInputStream sis = new SequenceInputStream(en);

FileOutputStream fos = new FileOutputStream("c:\\splitfiles\\0.bmp");

byte[] buf = new byte[1024];

int len = 0;

while ((len = sis.read(buf)) != -1) {
fos.write(buf, 0, len);
}

fos.close();
sis.close();
}

public static void splitFile() throws IOException {
FileInputStream fis = new FileInputStream("c:\\1.bmp");

FileOutputStream fos = null;

byte[] buf = new byte[1024 * 1024];

int len = 0;
int count = 1;
while ((len = fis.read(buf)) != -1) {
fos = new FileOutputStream("c:\\splitfiles\\" + (count++) + ".part");
fos.write(buf, 0, len);
fos.close();
}

fis.close();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: