当前位置:网站首页>NIO例子
NIO例子
2022-06-23 09:32:00 【Linging_24】
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();
}
}
边栏推荐
猜你喜欢
随机推荐
Jog运动模式
Basic use of lua
[MRCTF2020]Ez_ bypass
UEFI源码学习3.7 - NorFlashDxe
Redis学习笔记—数据类型:字符串(string)
S5P4418裸机编程的实现(替换2ndboot)
UEFI 源码学习4.1 - PciHostBridgeDxe
Typora设置图片上传服务
Redis learning notes master-slave copy
Best time to buy and sell stock II
Leetcode topic analysis contains duplicate II
Combination sum II of leetcode topic analysis
Simple student management
Cesium加载正射影像方案
一个采用直接映射方式的32KB缓存......存储器课后习题
Redis学习笔记—数据类型:哈希(hash)
The difference between ARM processor and 51 single chip microcomputer programming
Redis学习笔记—Redis与Lua
Redis learning notes RDB of persistence mechanism
Redis learning notes - single key management

![[GXYCTF2019]BabyUpload](/img/82/7941edd523d86f7634f5532ab97717.png)


![[极客大挑战 2019]HardSQL](/img/73/ebfb410296b8e950c9ac0cf00adc17.png)

