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