private static void readNIO() {
try {
// 第一步:获取通道
FileInputStream fis1 = new FileInputStream("Maven_IP.txt");
// FileChannel:从文件读取数据的
FileChannel channel = fis1.getChannel();
// 第二步:创建缓冲区
ByteBuffer bb = ByteBuffer.allocate(1024);
// 第三步:将数据从通道读到缓冲区
int count = channel.read(bb);
// java.nio.HeapByteBuffer[pos=151 lim=1024 cap=1024]
// 将position是位置:limit:上限; capacity:容量;
System.out.println(bb);
// java.nio.HeapByteBuffer[pos=0 lim=151 cap=1024]
//重设一下position=0
bb.flip();
//
System.out.println(bb);
// 剩余的字节数 remaining(limit - position);=151-0>0
while (bb.remaining() > 0) {
// 获得字节!
System.out.print((char) bb.get());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
写文件:
private static void writeNIO() {
try {
// 第一步:获取通道
FileOutputStream fos = new FileOutputStream("my.txt");
// FileChannel:从文件读取数据的
FileChannel channel = fos.getChannel();
// 第二步:创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 第二步:将数据放入缓冲区
String[] strings = { "a", "b", "c", "f" };
for (int i = 0; i < strings.length; i++) {
buffer.put(strings[i].getBytes());
}
// 重设一下postion=0
buffer.flip();
// 第三步:把缓冲区数据写入通道中
channel.write(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
拷贝文件
public static void copyFileUseNIO(String src, String dst)
throws IOException {
// 声明源文件和目标文件
FileInputStream fi = new FileInputStream(new File(src));
FileOutputStream fo = new FileOutputStream(new File(dst));
// 获得传输通道channel
FileChannel inChannel = fi.getChannel();
FileChannel outChannel = fo.getChannel();
// 获得容器buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// 判断是否读完文件
int eof = inChannel.read(buffer);
if (eof == -1) {
break;
}
// 重设一下buffer的position=0,limit=position
buffer.flip();
// 开始写
outChannel.write(buffer);
// 写完要重置buffer,重设position=0,limit=capacity
buffer.clear();
}
inChannel.close();
outChannel.close();
fi.close();
fo.close();
}