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数据,那么只需要从通道里面读取数据就可以