怎么用java使用BufferedInputStream读取文本文件
1个回答
2016-07-03 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
/***
* @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 {
//关闭 BufferedInputStreamtry {
if (bufferedInput != null)
bufferedInput.close();
} catch (IOException ex) {
ex.printStackTrace();}}}/**
* @param args 命令行参数*/
* @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 {
//关闭 BufferedInputStreamtry {
if (bufferedInput != null)
bufferedInput.close();
} catch (IOException ex) {
ex.printStackTrace();}}}/**
* @param args 命令行参数*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询