黑马程序员技术交流社区
标题:
IO文件切割 可指定切割文件的大小
[打印本页]
作者:
fmi110
时间:
2015-8-8 14:38
标题:
IO文件切割 可指定切割文件的大小
IO
/*
需求:切割一个文件
分析: 1、将要分割的文件封装至流
2、目标文件封装至流
*/
import java.io.*;
import java.util.*;
class SplitFile
{
public static void main(String[] args) throws IOException
{
split();//切割的文件大小为3M
// merge();//合并文件
System.out.println("Hello World!");
}
public static void split() throws IOException //SIZE设置切割后每部分文件的大小
{
//切割文件
FileInputStream fin = new FileInputStream("d:\\迅雷绿色破解版.rar");
//切割成3个文件,定义输出流,轮流指向三个输出流
FileOutputStream fos = null;
//创建1M缓冲区
byte[] buf = new byte[1024*1024];
int len = 0;//int是32位,支持不了大于4G的内容
int SIZE = 5; //设置切割后每部分文件的大小
int count = 1;//用于命名生成文件的序号
int time = 0;
while((len=fin.read(buf))!=-1){
System.out.println("Cached... "+(float)len/(1024*1024)+"M ....");//在屏幕上输出提示缓冲的大小
if(time==0)
fos = new FileOutputStream("d:\\"+(count)+".part");
time++;//判断后加1
fos.write(buf,0,len); //单次写入文件
fos.flush();
System.out.println("flush...");
if(time>=SIZE){ //控制分割的文件的大小为 SIZE
System.out.println("******************* "+(count)+" part finished!!******************");
count++;
time = 0;
}
}
fos.close();
fin.close();
}
public static void merge() throws IOException
{
//集合接受流
ArrayList<FileInputStream> ar = new ArrayList<FileInputStream>();
//添加要合并的文件
ar.add(new FileInputStream("d:\\1.part"));
ar.add(new FileInputStream("d:\\2.part"));
//创建输出流
FileOutputStream fos = null;
final Iterator<FileInputStream> it = ar.iterator();//为保证传递给内部类后数据的一致性,用final修饰
//复写枚举,并传递给SequenceInputStream
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){
public boolean hasMoreElements(){
return it.hasNext();
}
public FileInputStream nextElement(){
return it.next();
}
};
SequenceInputStream sis = new SequenceInputStream(en);
//缓冲
byte[] buf = new byte[1024*1024];
int len;
fos = new FileOutputStream("d:\\mergeFile.jpg");
while((len=sis.read(buf))!=-1){
fos.write(buf,0,len);
fos.flush();
}
fos.close();
sis.close();
}
}
复制代码
作者:
fmi110
时间:
2015-8-8 14:44
自己顶一次 可以进入第21天的基础视频了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2