用java合并多个文件

版权声明:本文章由BlackCarDriver原创,欢迎评论和转载 https://blog.csdn.net/BlackCarDriver/article/details/89295352

情景

昨日翻看到我珍藏多年的几个MV,突然想合并到一起做成一个合集文件,
既然java有那么多文件操作的内置函数,顺便复习一下java文件操作,
或许日后还能用到。
方法很简单,首先将想要合拼的文件都放到一个指定的文件夹里,然后逐个
读取,用字节的形式全部复制到另外一个相同格式的同一个文件里。

实测结果

经过实测,合并后的MP4虽然能播放,但是播放完第一部分就停止播放。MP3则能够完美合并。
文本文件如txt,合并后可能会出现由于编码不同导致的中文显示成乱码。


MyCode

//用io流将指定目录下的全部指定格式的文件合并到combinfile里
package combinFileTest;
import java.io.*;
import java.util.Scanner;

public class main {
	public static void main(String[] args) throws IOException{
		File location = new File("D:\\TestCombin");	//指定操作的位置	" 
		String type = "txt";						//指定操作文件的类型
		File targer = new File(location.toString()+"\\combinfile."+type);
		File[] source = location.listFiles();
		//显示合拼顺序
		for( File i:source){
			String fn = i.getName();
			if(judgeSuffix(fn, type)){
				System.out.println(fn);
			}
		}
		//询问是否合拼
		System.out.println("The order is like above, sure to combin?");
		Scanner scn = new Scanner(System.in);
		if(scn.next().toLowerCase().charAt(0)=='y'){
			//合并文件
			FileOutputStream output = new FileOutputStream(targer);
			for(File i:source){
				 if(judgeSuffix(i.getName(), type)==false) continue; //跳过不是指定格式的文件
				 FileInputStream input  = new  FileInputStream (i);
				 byte[] b = new byte[1024];
				 int n;
			     while((n=input.read(b))!=-1){
			        output.write(b, 0, n);
			     }
			     input.close();
			     System.out.println(i.getName()+" copy scuess!");
			}
			output.close();
		}
		System.out.println("ok");
		return;
	}
	//判断后缀名
	public static boolean judgeSuffix(String fn, String s){
		 String suffix = fn.substring(fn.lastIndexOf(".") + 1);
		 return (suffix.equals(s));
	}
}

猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/89295352
今日推荐