文件的拆分合并

效率很是低下,一天时间就琢磨了这个文件拆分合并,而且是byte型的,可能中文会出现乱码。

但不管怎样,还是很有收获的。

文件合并:

要注意选择好文件夹之后确定文件的绝对路径包含你想要的字符

getAbsoluteFile()返回的是一个File类对象,这个File对象表示是当前File对象的绝对路径名形式
getAbsolutePath()返回的是一个字符串,这个字符串就是当前File对象的绝对路径名的字符串形式

arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 

参数:src表示源数组,srcPos表示源数组要复制的起始位置,desc表示目标数组,length表示要复制的长度。

先确定文件的个数,之后

创建输入流写入准备拷贝的文件

创建输出流将拷贝的文件放入新文件中。。。。

文件拆分:

FileInputStream读入要拆分的文件

byte[] 设置字节限制

FileOutputStream将读出来的文件创建新的文件记录

.flush()刷新输出流,并强制写出所有缓冲区的数据

.close()关闭流

 

package bank;

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.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;



public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
	/*File f = new File("f:/lol.txt");
	System.out.println("f的绝对路径"+f.getAbsolutePath());
	System.out.println("f是否是文件夹"+f.isDirectory());
	System.out.println("f是否是文件"+f.isFile());
	System.out.println("f的文件长度"+f.length());
	*/
	splitDemo();//文件分割
	sequenceDemo();//文件合并
	
	
	}

	private static void sequenceDemo() throws IOException{
		// TODO Auto-generated method stub
		File f = new File("f:/new");
		File[] fs = f.listFiles();
		int length = 0;
		int temp = 0;
		for(File file : fs ){
			if(( file.getAbsolutePath()).contains("lol")){
				length = length + (int) file.length();
			}
			
		}
		byte[] result = new byte[length];
		for(File file : fs){
			if(file.getAbsolutePath().contains("lol")){
				byte[] b = new byte [(int) file.length()];
				InputStream is = new FileInputStream(file);
				is.read(b);
				System.arraycopy(b, 0, result, temp, b.length);
				temp +=b.length;
				
			}
		}
		File f1 = new File("f:/new/lolo.txt");
		OutputStream ops = new FileOutputStream(f1);
		ops.write(result);
		
	}

	private static void splitDemo() throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream("f:/new/lol.txt");
		FileOutputStream fos = null;
		byte [] buf = new byte[1024];
		int len,count = 0;
		
		while((len = fis.read(buf))!=-1){
			fos = new FileOutputStream("f:/new/lol"+(count++)+".txt");//写好output的文件
			fos.write(buf,0,len);//写入数据
			fos.flush();//刷新输出流,并强制写出所有缓冲区的数据
			fos.close();
		}
		fis.close();
		
	}
	}
	

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值