Java常用的对文件的读取方式基本包括:

  • BufferedReader -> readLine(): 按行读取文件,直到读取内容==null
  • FileInputStream -> read() : 按字节读取文件,直到读取内容==-1
  • InputStreamReader -> read() : 按字符读取文件,直到读取内容==-1
  • RandomAccessFile -> seek() : 可以指定文件的读取位置,以字节为单位
  • Scanner -> nextLine() : 按行读取文件,直到hasNextLine() == false
 public class ReadFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[10];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
// System.out.println("上面读取了10个字节");
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
} /**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file),"gbk");
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
} } catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
} /**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
} /**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
} /**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFile.readFileByBytes(fileName);
ReadFile.readFileByChars(fileName);
ReadFile.readFileByLines(fileName);
ReadFile.readFileByRandomAccess(fileName);
}
}

Java对文件的读取方式以及它们的优缺点的更多相关文章

  1. java通过文件路径读取该路径下的所有文件并将其放入list中

    java通过文件路径读取该路径下的所有文件并将其放入list中   java中可以通过递归的方式获取指定路径下的所有文件并将其放入List集合中.假设指定路径为path,目标集合为fileList,遍 ...

  2. 总结java创建文件夹的4种方法及其优缺点-JAVA IO基础总结第三篇

    本文是Java IO总结系列篇的第3篇,前篇的访问地址如下: 总结java中创建并写文件的5种方式-JAVA IO基础总结第一篇 总结java从文件中读取数据的6种方法-JAVA IO基础总结第二篇 ...

  3. java 资源文件的读取

    Java将配置文件当作一种资源(resource)来处理,并且提供了两个类来读取这些资源,一个是Class类,另一个是ClassLoader类. gradle 项目 项目目录结构  用Class类加载 ...

  4. java中文件的读取和写入

    //首先要顶一个file文件用来存放要读取的文件 File f=new File("c:/test/aa.txt"); //在实例化一个输入流,并把文件对象传到里面 FileInp ...

  5. java从文件中读取数据然后插入到数据库表中

    实习工作中,完成了领导交给的任务,将搜集到的数据插入到数据库中,代码片段如下: static Connection getConnection() throws SQLException, IOExc ...

  6. Applet web端对文件的读取方式

    转载:http://www.exam8.com/computer/Java/zonghe/200708/659876.html ---- 我们知道,在Java Applet中出于安全性考虑,Apple ...

  7. Java 对文件的读取操作

    package pack; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; ...

  8. 多个yml文件的读取方式

    1配置pom.xml文件,以下配置将默认激活-dev.yml配置文件<profiles>        <profile>            <id>dev&l ...

  9. Java—从文件中读取数据

    1.FileInputStream() // 构建字节输入流对象,参数为文件名 FileInputStream fin = new FileInputStream("message" ...

随机推荐

  1. 【angular5项目积累总结】遇到的一些问题以及解决办法

    1.项目中字符串特别是\r\n,替换成br之后,在页面换行无法生效? 答:绑定元素 innerHTML. <div class="panel-body" [innerHTML ...

  2. python爬虫实战(八)--------知乎

    相关代码已经修改调试成功----2017-4-22 一.说明 1.目标网址:知乎登入后的首页 2.实现:如图字段的爬取 zhihu_question表: zhihu_answer表: 3.数据:存放在 ...

  3. css的四种书写方式

    优先级: 外部样式 < 内部样式表 < 内联样式表: 优先级,即:同名的选择器右边的会覆盖左边 1.内部样式表 <head> <style> /*内部样式表,一般用 ...

  4. 在IIs上部署asp.net core2.1项目

    转自:https://www.cnblogs.com/jasonduan/p/9193702.html 在IIS上部署你的ASP.NET Core 2.1项目   1.在控制面板→程序→启用或关闭Wi ...

  5. 撩课-Java每天10道面试题第7天

    撩课Java+系统架构 视频 点击开始学习 61.什么是并发修改异常? 什么是并发修改异常: 当我们在遍历实现了collection接口 与iterator接口的集合时(List.Set.Map), ...

  6. 【Java学习经历系列-1】19岁的我,没遇见生命中的她,却遇见了java

    [写在前面]正直青春年少的你,遇到了你的她了吗?还是你也和我们今天的主人公一样,在最美好的年级,正在为你的初衷努力着,坚持着,奔波着..... 作者:李伟   我的黑客时代 01 大学专业是电子信息工 ...

  7. mysql数据库重点(基础优化)

    ### Mysql性能优化 尽量不要写select * ,如果需要全表数据,使用select 加所有字段列名称查询代替* 尽量减少字段列的数学计算,如:where num * 2 >= 30,可 ...

  8. JDBC数据库连接池

    用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长.假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大的浪费数据库的资源,并且极易造成数据库 ...

  9. 第一个Windows窗口应用程序

    学习目的 熟悉开发工具Visual C++ 6.0和MSDN 2001的使用. 应用Windows API函数, 手工编写具有最基本构成的Windows窗口应用程序(包含WinMain入口函数, 消息 ...

  10. 基于.Net下整合FastReport,实现条码标签批量打印

    一. 准备工作 1. 点击此下载支持.Net4.0的 FastReport ,安装后并破解 2. VS2012 工具箱中,新建选项卡,添加 %安装目录%\Framework 4.0\FastRepor ...