Java新IO所使用的结构
更接近于操作系统执行I/O的方式:通道和缓冲器。通道是包含煤层的矿藏,缓冲器则是派送到矿藏的卡车。唯一与通道交互的缓冲器是ByteBuffer。
旧I/O库中有三个类被修改了,用以产生FileChannel
public class GetChannel {
public static void main(String[] args) throws IOException {
FileChannel fc = new FileOutputStream("data").getChannel();
fc.write(ByteBuffer.wrap("some text ".getBytes()));
fc.close();
fc = new RandomAccessFile("data", "rw").getChannel();
fc.position(fc.size());
fc.write(ByteBuffer.wrap("some more ".getBytes()));
fc.close();
fc = new FileInputStream("data").getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
fc.read(buf);
// 让ByteBuffer做好让别人读的准备
buf.flip();
while (buf.hasRemaining())
System.out.print((char) buf.get());
}
}
转换数据
public class BufferToText {
public static void main(String[] args) throws IOException {
//=======================第一次============================
FileChannel fc = new FileOutputStream("data").getChannel();
fc.write(ByteBuffer.wrap("some text ".getBytes()));
fc.close();
fc = new FileInputStream("data").getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
fc.read(buf);
buf.flip();
System.out.println(buf.asCharBuffer()); //乱码
// 返回到数据开始的地方
buf.rewind();
//=======================第二次============================
String encoding = System.getProperty("file.encoding");
System.out.println("system file encoding is " + encoding);
fc = new FileOutputStream("data").getChannel();
// 进行decode
fc.write(ByteBuffer.wrap("some text ".getBytes("UTF-16BE")));
fc.close();
fc = new FileInputStream("data").getChannel();
buf.clear();
fc.read(buf);
buf.flip();
System.out.println(buf.asCharBuffer());
//=======================第三次============================
fc = new FileOutputStream("data").getChannel();
buf = ByteBuffer.allocate(24);
// 进行encode
buf.asCharBuffer().put("Some text");
fc.write(buf);
fc.close();
fc = new FileInputStream("data").getChannel();
buf.clear();
fc.read(buf);
buf.flip();
System.out.println(buf.asCharBuffer());
}
}
|