javanio中FileChannel寫入檔案write,追加檔案,以及多檔案合併
阿新 • • 發佈:2019-01-30
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();