SequenceInputStream 实现文件的切割与合并

本文详细介绍了如何使用Java的SequenceInputStream类来高效地实现文件的切割与合并操作,通过实例代码展示了其工作原理和应用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SequenceInputStream实现文件的切割与合并 

package file;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
//文件切割合并
public class Demo11 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//文件切割
		spilt(new File("D:\\music\\a.mp3"),"D:\\music\\");
		System.out.println("文件切割完成....");
		
		File srcFile = new File("D:\\music\\");
		merge(srcFile,new File("D:\\music\\"),"b.mp3");
		System.out.println("文件合并完成....");
	}

	private static void spilt(File src, String dir) throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream(src);
		FileOutputStream fos= null ;
		
		int len = 0;
		byte[] buf = new byte[1024*1024];
			
			int count=1;
			while((len = fis.read(buf)) != -1){
				int i= count++;
				fos = new FileOutputStream(dir+i+".mp3");
				fos.write(buf, 0, len);
			}
		fos.close();
		fis.close();
	}
	 //切割的文件位置,合并后文件存放的文件位置,合并后的文件名
	private static void merge(File srcFile,File destFile,String fileName) throws IOException {
		// TODO Auto-generated method stub
		//LinkedHashSet<InputStream> linkhashset
		
		//如果文件路径不存在则创建
		if(!destFile.isFile()){
			destFile.mkdirs();
		}
		//获取并存放切割的所有文件
		File[] files = srcFile.listFiles();
		//将切割的文件放入LinkedHashSet集合中
		LinkedHashSet<InputStream> linkedhashset =new LinkedHashSet<InputStream>();
		for(int i=1 ;i< files.length;i++) {
	    	linkedhashset.add(new FileInputStream(new File(srcFile,i+".mp3")));
	    }
	
		final Iterator<InputStream> it =  linkedhashset.iterator();
	    //SequenceInputStream合并流 
	    SequenceInputStream sis = new SequenceInputStream(
	    		//使用Eunmeration(列举)将文件列举出来
	    		new Enumeration<InputStream>(){

					@Override
					public boolean hasMoreElements() {
						// TODO Auto-generated method stub						
						return it.hasNext();
					}
					@Override
					public InputStream nextElement() {
						// TODO Auto-generated method stub
						return it.next();
					}	    		    			
	    		} 	
	    	);
	    //合并文件
	    OutputStream fos = new FileOutputStream(new File(destFile,fileName));
	    int len = 0;
	    byte[] buf = new byte[1024];
	    while((len = sis.read(buf))!= -1){
	    	fos.write(buf,0,len);	    	
	    }
	    
	    fos.close();
	    sis.close();
	}
	

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值