例1:将hello,world!输出到文件a.txt中
public class NIOFilechannel {
public static void main(String[] args) throws IOException {
// 创建一个输出流
FileOutputStream fos = new FileOutputStream("C:\\Users\\whatsoooever\\Desktop\\a.txt");
// 获取输出流的channel
FileChannel fc = fos.getChannel();
// 创建一个缓冲区,并分配1024个字节
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// 将字符串转化为字节写入到缓冲区中
byteBuffer.put("hello,world!".getBytes());
// 由于要从缓冲区中读数据写入到channel中,所以先反转
byteBuffer.flip();
fc.write(byteBuffer);
fc.close();
fos.close();
}
}
例2:将文件a.txt中的内容打印到控制台上
public class NIOFilechannel {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\whatsoooever\\Desktop\\a.txt");
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bf = ByteBuffer.allocate((int)file.length());
fc.read(bf);
System.out.println(new String(bf.array()));
fc.close();
fis.close();
}
}
例3:将文件a.txt中的内容复制到b.txt中
public class NIOFilechannel {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:\\Users\\whatsoooever\\Desktop\\a.txt");
FileChannel fc1 = fis.getChannel();
FileOutputStream fos = new FileOutputStream("C:\\Users\\whatsoooever\\Desktop\\b.txt");
FileChannel fc2 = fos.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
// 重要操作,一定要clear
byteBuffer.clear();
int read = fc1.read(byteBuffer);
if (read == -1) {
break;
}
// 读写切换
byteBuffer.flip();
fc2.write(byteBuffer);
}
fc1.close();
fc2.close();
fis.close();
fos.close();
}
}
例4:通过tansferfrom的方式将文件a.txt中的内容复制到c.txt中,无需bytebuffer
public class NIOFilechannel {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\whatsoooever\\Desktop\\a.txt");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("C:\\Users\\whatsoooever\\Desktop\\c.txt");
FileChannel resource = fis.getChannel();
FileChannel des = fos.getChannel();
des.transferFrom(resource,0,file.length());
des.close();
resource.close();
fis.close();
fos.close();
}
}
例5:通过mappedByteBuffer将文件a.txt直接在内存(堆外内存)修改,操作系统不需要拷贝一次
public class MappedByteBufferTest {
public static void main(String[] args) throws IOException {
RandomAccessFile acf = new RandomAccessFile("C:\\Users\\whatsoooever\\Desktop\\a.txt","rw");
FileChannel fc = acf.getChannel();
// 参数1:使用读写模式
// 参数2:可以直接修改的起始位置
// 参数3:将文件映射到内存的大小
MappedByteBuffer mb = fc.map(FileChannel.MapMode.READ_WRITE,0,5);
mb.put(0,(byte)'H');
mb.put(3,(byte)'Z');
fc.close();
acf.close();
}
}
原文件中内容:hello,world!
新文件中内容:HelZo,world!