AsynchronousFileChannel
Futrue读取
Path path = Paths.get("/Users/mzx/Desktop/java/nio/test4.txt")
//创建
AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.READ)
ByteBuffer bb = ByteBuffer.allocate(1024)
Future<Integer> future = afc.read(bb, 0)
while (!future.isDone()) {
System.out.println("isDone")
}
bb.flip()
System.out.println(new String(bb.array(),0 ,bb.array().length))
afc.close()
CompletionHander读取
Path path = Paths.get("/Users/mzx/Desktop/java/nio/test4.txt");
AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer bb = ByteBuffer.allocate(1024);
afc.read(bb, 0, bb, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println(result);
System.out.println(new String(attachment.array()));
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
exc.printStackTrace();
}
});
System.out.println("finish");
Future写数据
Path path = Paths.get("/Users/mzx/Desktop/java/nio/test4.txt")
//创建
AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)
ByteBuffer bb = ByteBuffer.allocate(1024)
bb.put("AsynchronousFileChannel".getBytes())
bb.flip()
Future<Integer> future = afc.write(bb, 0)
while (!future.isDone()) {
System.out.println("isDone")
}
System.out.println("finish")
afc.close()
CompletionHander写数据
Path path = Paths.get("/Users/mzx/Desktop/java/nio/test4.txt")
//创建
AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)
//ByteBuffer bb = ByteBuffer.wrap("AsynchronousFileChannel - CompletionHandler".getBytes())
ByteBuffer bb = ByteBuffer.allocate(1024)
bb.put("AsynchronousFileChannel - dawda".getBytes())
bb.flip()
afc.write(bb, 0, bb, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println(result)
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
exc.printStackTrace()
}
})
System.out.println("finish")
Charset
//字符集对象
Charset charset = Charset.forName("UTF-8")
//编码器对象
CharsetEncoder ce = charset.newEncoder()
CharBuffer cb = CharBuffer.allocate(1024)
cb.put("你好helloworld")
cb.flip()
//编码
ByteBuffer bb = ce.encode(cb)
for (int i = 0
System.out.println(bb.get())
}
//解码
bb.flip()
CharsetDecoder cd = charset.newDecoder()
CharBuffer dcb = cd.decode(bb)
//你好helloworld
System.out.println(dcb)
//gbk方式
Charset gbk = Charset.forName("GBK")
CharsetDecoder gbkcd = gbk.newDecoder()
bb.flip()
CharBuffer gbkcb = gbkcd.decode(bb)
//浣犲ソhelloworld
System.out.println(gbkcb)
SortedMap<String, Charset> map = Charset.availableCharsets();
for (Map.Entry<String, Charset> sce : map.entrySet()) {
System.out.println(sce.getKey() + " - " + sce.getValue());
}
System.out.println(Charset.defaultCharset());
System.out.println(Charset.isSupported("UTF-8"));