io流的一種:
package com.cxy.ssp.Automic; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.atomic.AtomicStampedReference; //通過nio實現文件io public class Demo3 { public static void main(String[] args) throws Exception{ //1 創建輸出流 FileOutputStream fileOutputStream = new FileOutputStream("bas.txt");
//構建通道 FileChannel channel = fileOutputStream.getChannel();
//創建緩存區 ByteBuffer buffer = ByteBuffer.allocate(1024); // String str ="hello world";
//將數據放入緩沖區 buffer.put(str.getBytes()); try {
//需要清空緩沖區的標記,再進行操作 buffer.flip();
//將內容寫到通道中 channel.write(buffer); } catch (IOException e) { e.printStackTrace(); } fileOutputStream.close(); } }
package com.cxy.ssp.Automic; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Demo4 { public static void main(String[] args) throws Exception{ //先構建輸入流, FileInputStream fileInputStream = new FileInputStream("bas.txt"); //通過流獲取通道 FileChannel channel = fileInputStream.getChannel(); //准備緩存沖區 ByteBuffer buffer = ByteBuffer.allocate(1024); //從通道里面讀取數據。是字節數據 channel.read(buffer); //打印內容 System.out.println(new String(buffer.array())); //關閉 fileInputStream.close(); } }
package com.cxy.ssp.Automic; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; public class Demo5 { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("bas.txt"); FileOutputStream fileOutputStream = new FileOutputStream("b.txt"); FileChannel channel = fileInputStream.getChannel(); FileChannel channel1 = fileOutputStream.getChannel(); channel1.transferFrom(channel,0,channel.size()); channel1.close(); channel.close(); } }
思路:首先構建輸入或者輸出流,然后通過輸出或者輸入流建立通道,channle
創建緩沖區,進行緩存區的操作,通道的操作
以上代碼總結:
1 輸入輸出是跟你電腦而言的,輸出到電腦意外,就是輸出,電腦上就是輸入
2 輸出流,需要向緩沖區里面put字節數據,
3 輸入流:不需要向緩沖區里面進行put數據,那么只需要從通道里面讀取數據就可以
