public class NIOFileChannel01 { public static void main(String[] args) throws Exception { String str = "hello,帥鍋"; //創建一個輸出流->channel FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt"); //通過 fileOutputStream 獲取 對應的 FileChannel //這個 fileChannel 真實 類型是 FileChannelImpl FileChannel fileChannel = fileOutputStream.getChannel(); //創建一個緩衝區 ByteBuffer ByteBuffer byteBuffer = ByteBuffer.allocate(1024); //將 str 放入 byteBuffer byteBuffer.put(str.getBytes()); //對byteBuffer 進行flip byteBuffer.flip(); //將byteBuffer 數據寫入到 fileChannel fileChannel.write(byteBuffer); fileOutputStream.close(); } }
public class NIOFileChannel02 { public static void main(String[] args) throws Exception { //創建文件的輸入流 File file = new File("d:\\file01.txt"); FileInputStream fileInputStream = new FileInputStream(file); //通過fileInputStream 獲取對應的FileChannel -> 實際類型 FileChannelImpl FileChannel fileChannel = fileInputStream.getChannel(); //創建緩衝區 ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length()); //將 通道的數據讀入到Buffer fileChannel.read(byteBuffer); //將byteBuffer 的 字節數據 轉成String System.out.println(new String(byteBuffer.array())); fileInputStream.close(); } }