Java——新IO 通道

时间:2021-05-18 15:12:10

Java——新IO 通道

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; //=================================================
// File Name : FileChannel_demo
//------------------------------------------------------------------------------
// Author : Common //主类
//Function : FileChannel_demo
public class FileChannel_demo { public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
String info[] = {"123","456","789"};
File f = new File("/home/common/software/coding/HelloWord/HelloWord/out.txt");//路径
FileOutputStream output = null;
output = new FileOutputStream(f);
FileChannel fout = null; //声明输出的通道
fout = output.getChannel(); //得到输出的文件通道
ByteBuffer buf = ByteBuffer.allocate(1024); //开辟缓冲
for(int i=0;i<info.length;i++){
buf.put(info[i].getBytes());
}
buf.flip(); //重设缓冲区,准备输出
fout.write(buf); //输出
fout.close();
output.close(); } }

 读写文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; //=================================================
// File Name : FileChannel_demo
//------------------------------------------------------------------------------
// Author : Common //主类
//Function : FileChannel_demo
public class FileChannel_demo { public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根 File f1 = new File("/home/common/software/coding/HelloWord/HelloWord/out.txt");//路径
File f2 = new File("/home/common/software/coding/HelloWord/HelloWord/outnote.txt");//路径
FileInputStream input = null;
FileOutputStream output = null;
input = new FileInputStream(f1);
output = new FileOutputStream(f2);
FileChannel fin = null; //声明输入的通道
FileChannel fout = null; //声明输出的通道
fin = input.getChannel(); //得到输入的文件通道
fout = output.getChannel(); //得到输出的文件通道
ByteBuffer buf = ByteBuffer.allocate(1024); //开辟缓冲
int temp = 0; //声明变量接收内容
while((temp=fin.read(buf)) != -1){
buf.flip();
fout.write(buf);
buf.clear();
}
fin.close();
fout.close();
input.close();
output.close(); } }

Java——新IO 通道

Java——新IO 通道