public class Main3 {
/**
* nio读取文件中的数据
* @param args
*/
public static void main(String[] args) throws IOException {
readThenWrite();
}
/**
* nio读取文件中的数据
* 文件 -> channel -> buffer
* @throws IOException
*/
public static void read() throws IOException{
// 获取输入流
FileInputStream fis = new FileInputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\read.txt");
// 获取通道
FileChannel readChannel = fis.getChannel();
// 创建一个1024字节大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 从通道读取数据到缓冲区,并返回读取的字节数
int readBytes = readChannel.read(buf);
// 读取的字节数不等于-1,说明有数据
while(readBytes != -1){
byte[] bs = new byte[readBytes];
// 由写模式切换为读模式
buf.flip();
// 缓冲区还有数据可以读
while(buf.hasRemaining()){
buf.get(bs);
String str = new String(bs, 0, readBytes);
System.out.println(str);
}
// 清空缓冲区数据
buf.clear();
// 再次从通道中读取数据到缓冲区,知道没有数据
readBytes = readChannel.read(buf);
}
fis.close();
}
/**
* 写入文件 存在问题,待修改
* buffer -> channel -> 文件
* @throws IOException
*/
public static void write() throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\write.txt");
FileChannel channel = fos.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put("2312312312".getBytes(StandardCharsets.UTF_8));
System.out.println(buf.toString());
int writeBytes = channel.write(buf);
fos.close();
}
/**
* 文件复制
*/
public static void readThenWrite() throws IOException {
FileInputStream fis = new FileInputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\read.txt");
FileOutputStream fos = new FileOutputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\write.txt");
FileChannel readChannel = fis.getChannel();
FileChannel writeChannel = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(readChannel.read(buffer) != -1){
// 切换为读模式
buffer.flip();
writeChannel.write(buffer);
buffer.clear();
}
fis.close();
fos.close();
}
}
NIO例子
最新推荐文章于 2022-04-10 23:17:20 发布