java.io 读取文件

java.io 读取文件

java, io, nio, channel ...

package javaexe.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
/**
* @author ruben
*/
public class Read {

public static void main(String[] args) {

File aFile = new File("D:/2.txt");
BufferedReader bReader = null;
FileInputStream inFile = null;
String s = null;
try{

inFile = new FileInputStream(aFile);

} catch(FileNotFoundException e) {}

try {

bReader = new BufferedReader(new InputStreamReader(inFile, "UTF-8"));

} catch(UnsupportedEncodingException e) {}

try {

while(true) {

s = bReader.readLine();
if(s == null) break;
System.out.println(s);

}
} catch(IOException e) {}

System.out.println("读取文件完成!");
System.exit(0);
}
}

/************** 另一种方法 *******************/

package javaexe.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
/**
*
* @author ruben
*/
public class Channel {

public static void main(String[] args) {

File aFile = new File("D:/2.txt");
FileInputStream inFile = null;
FileChannel inChannel = null;
ByteBuffer bb = ByteBuffer.allocateDirect(4096);
Charset cs = Charset.forName("UTF-8");
StringBuffer sb = new StringBuffer(1024);

try{

inFile = new FileInputStream(aFile);

} catch(FileNotFoundException e) {}

inChannel = inFile.getChannel();

try {

while(inChannel.read(bb) != -1) {

bb.flip();
CharBuffer cb = cs.decode(bb);
sb.append(cb.toString());
bb.clear();

}

inFile.close();

} catch(IOException e) {}

System.out.println(sb.toString());
System.out.println(sb.length());

System.out.println("读取文件完成!");
System.exit(0);

}
}

不知道怎么格式化,哎!也只有将就了!!
第一个是原始的io操作方式,感觉比较简单。
后一种是加入了通道概念的新io,能够自己操作缓冲大小,类型,并且可以得到文件大小后再决定创建怎样的缓冲,并且可以使用镜像文件,可以提供读写双向能力。
个人测试效率没有太大差异,也许是单文件没有压力的原因!在字符集转换的时候,刚开始不知道在nio中如何使用转换,后来才知道了Charset.decode()方法。还比较简单。


/**
* Sometimes , the only way to stay sane is go a little crazy .
*/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值