javanio中FileChannel写入文件write,追加文件,以及多文件合并
来源:互联网 发布:淘宝十大创意网店 编辑:程序博客网 时间:2024/06/05 12:48
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 0
- javanio中FileChannel写入文件write,追加文件,以及多文件合并
- 合并文件的FileChannel方式
- Java 追加写入文件
- hdfs文件追加写入
- golang追加写入文件
- python print 追加写入文件中
- [C#] 文本写入文件,追加写入文件
- 利用fprintf进行文件操作--向文件中追加写入
- 利用fprintf进行文件操作--向文件中追加写入
- 对文件的追加写入
- 文件写入覆盖和追加
- Java追加写入文件方法
- JavaNIO实现文件复制
- JavaNIO循环读取文件
- java写入文件(文件末尾追加)
- vc++向txt文件中写入数据,追加数据
- Android追加换行写入内容到txt文件中
- 文件读取,写入(去除源文件内容)以及追加写入(保留原文件内容)
- 解决APP启动闪屏
- 矩阵连乘动态规划算法
- 英语单词词频统计
- 使用豆瓣音乐API笔记
- Java多线程学习笔记(一)——Java的非线程安全问题
- javanio中FileChannel写入文件write,追加文件,以及多文件合并
- 【Java】Java虚拟机
- PRISM 下载安装
- socket编程之bind()函数
- 通过JS判断打开PC或H5页面
- java提高篇(六)-----关键字static
- android模拟器配置之genymotion
- 安卓学习历程-第二天
- 表单提交示例(Jsp+Servlet+jQueryForm)