java:NIO讀寫檔案的示例
阿新 • • 發佈:2019-01-11
Java NIO(New IO)是從Java 1.4版本開始引入的一個新的IO API,可以替代標準的Java IO API。
NIO方式讀資料非常簡單,
建立一個緩衝區(ByteBuffer),通過一個FileChannel (從FileInputStream 建立)完成緩衝區的資料讀入;
NIO方式寫資料也簡單,
建立一個緩衝區(ByteBuffer),向其中填充資料;然後通過一個FileChannel (從FileOutputStream 建立)完成緩衝區的資料寫入;
注意:讀寫結束後,要呼叫FileChannel.close()關閉通道釋放資源。
下面是通過NIO進行檔案讀寫的java例項程式碼。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOSample{
/**
* NIO方式複製檔案<br>
* 目標檔案所在的資料夾如果不存在自動建立資料夾
* @param src 原始檔
* @param dst 目標檔案
* @throws IOException
*/
public static final void nioCopyFile(File src,File dst) throws IOException {
if(null==src||null==dst)
throw new NullPointerException("src or dst is null");
if(!src.exists()||!src.isFile())
throw new IllegalArgumentException(String.format("INVALID FIILE NAME(無效檔名) src=%s" ,src.getCanonicalPath()));
if (dst.exists() &&!dst.isFile()) {
throw new IllegalArgumentException(String.format("INVALID FIILE NAME(無效檔名) dst=%s",dst.getCanonicalPath()));
}
File folder = dst.getParentFile();
if (!folder.exists())
folder.mkdirs();
if(((src.length()+(1<<10)-1)>>10)>(folder.getFreeSpace()>>10))
throw new IOException(String.format("DISK ALMOST FULL(磁碟空間不足) %s",folder.getCanonicalPath()));
FileInputStream fin=null;
FileOutputStream fout = null;
FileChannel fic = null;
FileChannel foc = null;
try {
fin=new FileInputStream(src);
fout = new FileOutputStream(dst);
// 從FileInputStream建立用於輸入的FileChannel
fic = fin.getChannel();
// 從FileOutputStream 建立用於輸出的FileChannel
foc = fout.getChannel();
// 16KB緩衝區
ByteBuffer bb = ByteBuffer.allocate(1024<<4);
// 根據 read返回實際讀出的位元組數 中止迴圈
while(fic.read(bb)>0){
// 緩衝區翻轉用於輸出到foc
bb.flip();
foc.write(bb);
// 清空緩衝區用於下次讀取
bb.clear();
}
} finally {
// 安全釋放資源
if(null!=fic)
fic.close();
if(null!=foc)
foc.close();
if(null!=fin)
fin.close();
if(null!=fout)
fout.close();
}
}
}