learing java NIO 之 ReadFile
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; public class ReadFile { public static void main(String[] args) { try ( var fis = new FileInputStream("./src/com/serial/ReadFile.java"); FileChannel fcin = fis.getChannel();) { ByteBuffer bbuf = ByteBuffer.allocate(10); while (fcin.read(bbuf) != -1){ bbuf.flip(); Charset charset = Charset.forName("GBK"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cbuf = decoder.decode(bbuf); System.out.println(cbuf); bbuf.clear(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }