博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javanio中FileChannel写入文件write,追加文件,以及多文件合并
阅读量:4041 次
发布时间:2019-05-24

本文共 1903 字,大约阅读时间需要 6 分钟。

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();

    

你可能感兴趣的文章
从零实现简易播放器-0.音视频基本概念
查看>>
从零实现简易播放器-1.模拟视频播放
查看>>
从零实现简易播放器-2.opengl渲染yuv图像
查看>>
Windows下编译可调试的ffmpeg, 包含ffplay
查看>>
意外消息:ppsjy:[MyHookProc]__read web cfg: success ------ :
查看>>
从零实现简易播放器:4.ffmpeg 解码视频为yuv数据-使用avcodec_send_packet与avcodec_receive_frame
查看>>
56个民族的C++ map定义
查看>>
Yotta企业云盘如何实现保护文件安全
查看>>
区块链技术让Yotta企业云盘为行政事业服务助力
查看>>
yotta企业云盘助力制造行业创高峰
查看>>
Yotta企业云盘更好的为媒体广告业服务
查看>>
Yotta企业云盘助力旅游行业新发展
查看>>
Yotta企业云盘助力科技行业创高峰
查看>>
Yotta企业云盘更好地为教育行业服务
查看>>
Yotta企业云盘怎么帮助到能源化工行业
查看>>
企业云盘如何助力商业新发展
查看>>
医疗行业运用企业云盘可以带来什么样的提升
查看>>
教育数字智能化能为现有体系带来新的起点
查看>>
媒体广告业如何将内容资产进行高效地综合管理与利用
查看>>
能源化工要怎么管控核心数据
查看>>