FileChannel實現簡單的檔案拷貝
阿新 • • 發佈:2021-02-05
技術標籤:java
public class NIOFileChannel { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("C:\\Users\\xiatian\\Desktop\\1.txt"); FileChannel channel = fileInputStream.getChannel(); FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\xiatian\\Desktop\\2.txt"); FileChannel outChannel = fileOutputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); // read從channel讀到緩衝區 while(-1 != channel.read(byteBuffer)){ byteBuffer.flip(); // write從緩衝區寫到channel中 outChannel.write(byteBuffer); byteBuffer.clear(); } fileInputStream.close(); fileOutputStream.close(); } }