FileChannel主要用来进行对本地文件进行IO操作
1.public int read(ByteBuffer dst):从通道读取数据并放到缓存区中
2.public int write(ByteBuffer src):把缓冲区的数据写到通道中
3.public long transferFrom(ReadableByteChannel src,long position,long count):从目标通道中复制数据到当前通道
4.public long transferTo(long position,long count,WritableByteChannel target):把数据从当前通道复制给目标通道
本地文件写数据
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel01 {
public static void main(String[] args) throws Exception {
String s = "test";
FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/test.txt");
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(s.getBytes());
byteBuffer.flip();
fileChannel.write(byteBuffer);
fileOutputStream.close();
}
}
本地文件读数据
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel02 {
public static void main(String[] args) throws Exception {
File file = new File("/Users/liaowh/Desktop/test.txt");
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel fileChannel = fileInputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
fileChannel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
fileInputStream.close();
}
}
使用一个Buffer完成文件拷贝
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel03 {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/Users/liaowh/Desktop/test.txt");
FileChannel fileChannel01 = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/test2.txt");
FileChannel fileChannel02 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
while(true){
byteBuffer.clear();
int read = fileChannel01.read(byteBuffer);
if(read == -1){
break;
}
byteBuffer.flip();
fileChannel02.write(byteBuffer);
}
fileInputStream.close();
fileOutputStream.close();
}
}
使用transferFrom()完成文件拷贝
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class NIOFileChannel04 {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/Users/liaowh/Desktop/test.txt");
FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/dest.txt");
FileChannel source = fileInputStream.getChannel();
FileChannel dest = fileOutputStream.getChannel();
dest.transferFrom(source,0,source.size());
source.close();
dest.close();
fileInputStream.close();
fileOutputStream.close();
}
}