import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* nio示例
*/
public class ChannelTest {
/**
* 分散读取 和 聚集写入
* @throws IOException
*/
private static void test3() throws IOException {
//获取文件输入流
FileInputStream fis = new FileInputStream("e:/test.txt");
//获取输入通道
FileChannel isChannel = fis.getChannel();
//获取文件输出流
FileOutputStream fos = new FileOutputStream("e:/test_n2.txt");
//得到输出通道
FileChannel osChannel = fos.getChannel();
//定于多个缓冲区做数据分散
ByteBuffer buffer1 = ByteBuffer.allocate(4);
ByteBuffer buffer2 = ByteBuffer.allocate(1024);
ByteBuffer [] byteBuffers = { buffer1, buffer2 };
//从通道中读取数据到各个缓冲区
isChannel.read(byteBuffers);
//查询每个缓冲区是否读到数据
for (ByteBuffer byteBuffer : byteBuffers) {
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, byteBuffer.remaining()));
}
//聚集写入通道
osChannel.write(byteBuffers);
isChannel.close();
osChannel.close();
System.out.println("文件复制完成");
}
/**
* 文件复制
* @throws IOException
*/
private static void test2() throws IOException {
//源文件
File srcFile = new File("e:/test.txt");
//目标文件
File destFile = new File("e:/test_new.txt");
//得到文件输入流
FileInputStream fis = new FileInputStream(srcFile);
//得到文件输出流
FileOutputStream fos = new FileOutputStream(destFile);
//得到文件通道
FileChannel isChannel = fis.getChannel();
FileChannel osChannel = fos.getChannel();
//创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true){
System.out.println("1");
buffer.clear();
int flag = isChannel.read(buffer);
System.out.println("flag----" + flag);
if( flag == -1 ){
System.out.println("2");
break;
}
//已经读取数据,把缓冲区模式切换成可读模式
buffer.flip();
//把数据写出到缓冲区
osChannel.write(buffer);
}
isChannel.close();
osChannel.close();
System.out.println("文件复制完成");
}
/**
* 从文件中读数据
*/
public void test1(){
try {
//得到文件输入流
FileInputStream fis = new FileInputStream("e:/test.txt");
//需要得到文件通道对象
FileChannel channel = fis.getChannel();
//定义一个缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//读取数据至缓冲区
channel.read(buffer);
buffer.flip();
String rs = new String(buffer.array(),0,buffer.remaining());
System.out.println(rs);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 向文件中写入数据
*/
public void test(){
try {
//字节输出流向目标文件
FileOutputStream fos = new FileOutputStream("e:/test.txt");
//得到字节输出流对应通道
FileChannel channel = fos.getChannel();
//分配缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("Hello,World!".getBytes());
//翻转缓冲区
buffer.flip();
channel.write(buffer);
channel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
【java】【nio】【入门示例】
最新推荐文章于 2024-07-17 23:58:13 发布