并不是所有的IO流类都支持NIO操作的,支持的类有FileInputStream、FileOutputStream和RandomAccessFile。
/*文件读取,返回读取内容*/
public static String fileReader(File fileName){
String fileContent = null;
FileInputStream fis = null;
FileChannel fc = null;
ByteBuffer bb ;
try {
fis = new FileInputStream(fileName);
fc = fis.getChannel();
// 分配10000字节的非直接缓冲区
bb = ByteBuffer.allocate(10000);
/*通过通道将数据读入到bb里面*/
fc.read(bb);
/*这里一定不要省略--切换为读取模式*/
bb.flip();
fileContent = new String(bb.array());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fileContent;
}
/*
fileName:要写入的目标文件;
s:要写入的信息;
*/
public static void fileWriter(File fileName,String s){
String fileContent = null;
FileOutputStream fos = null;
FileChannel fc = null;
byte[] bts = s.getBytes();
try {
fc = new FileOutputStream(fileName).getChannel();
ByteBuffer bb = ByteBuffer.allocate(bts.length);
/*将bts放入bb里面*/
bb.put(bts);
//切换读取模式
bb.flip();
/*通过通道从缓冲区块读出到目标文件*/
fc.write(bb);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*进行文件复制*/
public static void copy(String srcFile,String destFile){
long begin = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel in = null;
FileChannel out =null;
ByteBuffer bb = null;
try {
/* get NIO read channel */
fis = new FileInputStream(srcFile);
in = fis.getChannel();
/* get NIO write channel*/
fos = new FileOutputStream(destFile);
out = fos.getChannel();
bb = ByteBuffer.allocate(100000);
int len = 0;
while((len = in.read(bb)) != -1){
/*在write前,set the limit and position*/
bb.flip();
/*write form position to limit */
out.write(bb);
/*init positon/limit/capcity,prepare to the next loop*/
bb.clear();
}
long end = System.currentTimeMillis();
System.out.println("use time :"+(end-begin));
out.close();
in.close();
fos.close();
fis.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
参考博文:NIO究竟是什么 ?