NIO之FileChannel

1、读取数据

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo1 {
  public static void main(String[] args) throws IOException {
    //创建FileChannel
    RandomAccessFile aFile = new RandomAccessFile("1.txt","rw");
    FileChannel inChannel = aFile.getChannel();

    //创建Buffer
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    //读取数据到Buffer
    inChannel.position(2);
    int bytesRead = inChannel.read(buffer);
    while (bytesRead != -1) {
      System.out.println("读取:" + bytesRead);
      buffer.flip();
      while (buffer.hasRemaining()){
        System.out.print((char) buffer.get());
      }
      buffer.clear();
      bytesRead = inChannel.read(buffer);
    }
    aFile.close();
    System.out.println("操作结束");
  }

}

2、写入数据

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class FileChannelDemo2 {
  public static void main(String[] args) throws IOException {
    //创建FileChannel
    RandomAccessFile aFile = new RandomAccessFile("1.txt", "rw");
    FileChannel inChannel = aFile.getChannel();

    //创建Buffer
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    String newData = "data atgugui";
    buffer.clear();
    buffer.put(newData.getBytes(StandardCharsets.UTF_8));
    buffer.flip();


    while (buffer.hasRemaining()) {
      inChannel.write(buffer);
    }
    inChannel.close();
    System.out.println("操作结束");
  }

}

3、传输数据

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class FileChannelDemo3 {
  public static void main(String[] args) throws IOException {
    //创建FileChannel
    RandomAccessFile aFile = new RandomAccessFile("1.txt", "rw");
    FileChannel fromChannel = aFile.getChannel();

    RandomAccessFile bFile = new RandomAccessFile("2.txt", "rw");
    FileChannel toChannel = bFile.getChannel();

    long position = 0;
    long size = fromChannel.size();

    toChannel.transferFrom(fromChannel, position, size);
    aFile.close();
    bFile.close();
    System.out.println("操作结束");
  }

}
上一篇:通信三要素


下一篇:MSYS2 更新源