public interface Channel extend Clonseable{}
.
写案例:
@Test
public void write() {
try {
//1.字节输出流到目标文件
FileOutputStream fos = new FileOutputStream("data01.txt");
//2.得到字节输出流对应的通道
FileChannel channel=fos.getChannel();
//3.分配缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
buffer.put("吴孟达,加油!".getBytes());
//4.把缓冲区切换成写出模式
buffer.flip();
channel.write(buffer);
channel.close();
System.out.println("写数据到文件中!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
读数据:
@Test
public void read(){
try {
//1.获取文件输入流
FileInputStream fis=new FileInputStream("data01.txt");
//2.获取文件输入流对应的文件通道
FileChannel channel = fis.getChannel();
//3.定义一个缓冲区
ByteBuffer buffer=ByteBuffer.allocate(11024);
//4.读取数据到缓冲区
channel.read(buffer);
//5.切换读模式,将位置置为0
buffer.flip();
//6.重点:这里使用buffer.remaining去截取buffer中真正有数据的部分,要不输出的是1024个字节内容,后面没有占满也输出
String message=new String(buffer.array(),0,buffer.remaining());
System.out.println(message);//吴孟达,加油!
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3.使用Buffer完成文件复制
@Test
public void copy() {
try {
//原文件
File srcFile = new File("C:\\Users\\24459\\Desktop\\client\\20200724194309755.png");
//复制后的目标文件
File destFile = new File("C:\\Users\\24459\\Desktop\\client\\备份.png");
//定义文件输入流
FileInputStream is = new FileInputStream(srcFile);
//定义文件输出流
FileOutputStream os = new FileOutputStream(destFile);
//文件输入通道
FileChannel isChannel = is.getChannel();
//文件输出通道
FileChannel osChannel = os.getChannel();
//创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
//重点:每次进来都得先请缓存
buffer.clear();
//将数据读到缓冲区
int flag = isChannel.read(buffer);
//当读取完了就退出!
if (flag==-1){
break;
}
//重置位置开始写
buffer.flip();
osChannel.write(buffer);
}
isChannel.close();
osChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
标签:10,java,NIO,文件,buffer,printStackTrace,ByteBuffer,catch,new
From: https://www.cnblogs.com/wmd-l/p/16599893.html