BufferedInputStream 如何读取文件

下面的例子演示如何使用BufferedInputStream类读取文本文件内容。

首先需要声明一个byte数组作为buffer,然后循环将文本内容循环读入到buffer中,并将buffer转换为字符串,打印到控制台。

/**
*
* @author outofmemory.cn
*/
public class Main {

/**
* 从文件中读取文本
*/
public void readFromFile(String filename) {

BufferedInputStream bufferedInput = null;
byte[] buffer = new byte[1024];

try {

//创建BufferedInputStream 对象
bufferedInput = new BufferedInputStream(new FileInputStream(filename));

int bytesRead = 0;

//从文件中按字节读取内容,到文件尾部时read方法将返回-1
while ((bytesRead = bufferedInput.read(buffer)) != -1) {

//将读取的字节转为字符串对象
String chunk = new String(buffer, 0, bytesRead);
System.out.print(chunk);
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//关闭 BufferedInputStream
try {
if (bufferedInput != null)
bufferedInput.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

/**
* @param args 命令行参数
*/
public static void main(String[] args) {
new Main().readFromFile("myFile.txt");
}
}

posted @ 2014-08-25 17:21  Kevin_Zhou_9  阅读(3279)  评论(0编辑  收藏  举报