RandomAccessFile拆分合并文件

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.util.Vector;

public class RandonFileAccessTest {
    public static void main(String[] args) throws IOException {
       
        splitFile("test.txt");
        mergeFile();
        mergeFile2();
    }
    
    
    //拆分文件
    public static void splitFile(String path) throws IOException{
        InputStream is = new FileInputStream(path);
        int len=0;
        byte[] buff = new byte[1024];
        int i = 1;
        while((len=is.read(buff))!=-1){
            RandomAccessFile raf = new RandomAccessFile("raf"+i+".txt", "rw");//raf1.txt raf2.txt 一共只有两个文件
            raf.write(buff,0,len);
            raf.close();
            i++;
        }
        is.close();
    }
    
  //合并文件
public static void mergeFile() throws IOException{ RandomAccessFile raf = new RandomAccessFile("raf3.txt", "rw"); InputStream is = null; for(int i=1;i<3;i++){ int len=0; is = new FileInputStream("raf"+i+".txt"); //一共就两个文件 byte[] buff = new byte[1024]; while((len=is.read(buff))!=-1){ raf.write(buff,0,len); } } is.close(); raf.close(); }
  //另一种方式的合并文件
public static void mergeFile2() throws IOException{ RandomAccessFile raf = new RandomAccessFile("raf4.txt", "rw"); InputStream is = null; Vector<InputStream> vt = new Vector<InputStream>(); for(int i=1;i<3;i++){ is = new FileInputStream("raf"+i+".txt");//raf1.txt raf2.txt vt.addElement(is); } SequenceInputStream sis = new SequenceInputStream(vt.elements()); int len=0; byte[] buff = new byte[1024]; while((len=sis.read(buff))!=-1){ raf.write(buff,0,len); } sis.close(); is.close(); raf.close(); } }

 

转载于:https://www.cnblogs.com/Iqiaoxun/p/6021146.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值