package demo;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.io.*;
public class NIOReadDemo {
public static void main(String[] args){
FileInputStream fis=null;ByteBuffer bb=null;FileChannel fc=null;String text="";
try {
fis=new FileInputStream("E://123.txt");//采用文件流打开文件
fc=fis.getChannel();//从文件中获取一个通道
bb=ByteBuffer.allocate(1024);//建立一个ByteBuffer的容器 大小为1024(其实就是一个byte数组)
int readCount=fc.read(bb);//把数据从通道 读取到ByteBuffer里面 返回读取的个数
while(readCount!=-1){//判断读取是否为 -1 要是为-1则表示到达文件结尾
byte[] b=new byte[1024];//建立一个字节数组
if(bb.hasArray()){//先判断ByteBuffer对象里面是否有数据
b=bb.array();//把ByteBuffer对象 当作一个byte数组返回
}
text =text+new String(b,0,readCount);//对byte数组对象从新组装为字符串
System.out.println(text);//打印
readCount=fc.read(bb);//继续读取
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fis!=null){try {fis.close();} catch (IOException e) {}}
}
}
}
import java.nio.*;
import java.nio.channels.FileChannel;
import java.io.*;
public class NIOReadDemo {
public static void main(String[] args){
FileInputStream fis=null;ByteBuffer bb=null;FileChannel fc=null;String text="";
try {
fis=new FileInputStream("E://123.txt");//采用文件流打开文件
fc=fis.getChannel();//从文件中获取一个通道
bb=ByteBuffer.allocate(1024);//建立一个ByteBuffer的容器 大小为1024(其实就是一个byte数组)
int readCount=fc.read(bb);//把数据从通道 读取到ByteBuffer里面 返回读取的个数
while(readCount!=-1){//判断读取是否为 -1 要是为-1则表示到达文件结尾
byte[] b=new byte[1024];//建立一个字节数组
if(bb.hasArray()){//先判断ByteBuffer对象里面是否有数据
b=bb.array();//把ByteBuffer对象 当作一个byte数组返回
}
text =text+new String(b,0,readCount);//对byte数组对象从新组装为字符串
System.out.println(text);//打印
readCount=fc.read(bb);//继续读取
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fis!=null){try {fis.close();} catch (IOException e) {}}
}
}
}