javanio中FileChannel写入文件write,追加文件,以及多文件合并

2 篇文章 0 订阅

FileChannel   追加写入文件实现方法如下:

File file = new File(filename) ;
            if(!file.exists()){
                createFile(filename,"rwxr-x---") ;
            }
            FileOutputStream fos = null;
            int rtn =0 ;
            try {

                fos = new FileOutputStream(file,appendable);
                FileChannel fc = fos.getChannel();

                ByteBuffer bbf = ByteBuffer.wrap(bytes);
                bbf.put(bytes) ;
                bbf.flip();
                fc.write(bbf) ;

                fc.close();
                fos.flush();
                fos.close();
        }catch (IOException e) {
            rtn = 1 ;
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

fos = new FileOutputStream(file ,appendable) , 如果appendable为true,则表示追加到文件中写入。

如果APPendable为false,则上述代码是重新生成文件,会覆盖之前的文件内容。

注意:filechannel 的方法write(ByteBuffer src,long position),position为从文件的位置开始写入,如果fos=new FileOutputStream(file,false),跟write()一样也是会覆盖文件,同时生成的文件position位置之前的数据会全部为0。如下截图:



下图是FileOutputStream(file,true)时filechannel.write(byte,100)执行后效果,是在原来文件的基础上,增加100个为0的填充,然后再写真正的数据9,可以理解成position就是要新写入的文件空处position的位置。


总结,文件的追加写入,还是写成新的文件,是由FileOutputStream决定,而不是filechannel决定的,在写文件时注意,特别二进制文件不易查看。filechannel写的新文件,由appendable决定是替换原文件,还是追加到原文件中。


2.多文件合并的实现,主要是channel的transferTo() 方法

	FileChannel mFileChannel = new FileOutputStream(combfile).getChannel();
          FileChannel inFileChannel;

          for(String infile : fileArray){
              File fin = new File(infile) ;
              inFileChannel = new FileInputStream(fin).getChannel();
              inFileChannel.transferTo(0, inFileChannel.size(),
                      mFileChannel);

              inFileChannel.close();

          }
          mFileChannel.close();







    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值