Java对文件的读取方式以及它们的优缺点
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对文件的读取方式以及它们的优缺点的更多相关文章
- java通过文件路径读取该路径下的所有文件并将其放入list中
java通过文件路径读取该路径下的所有文件并将其放入list中 java中可以通过递归的方式获取指定路径下的所有文件并将其放入List集合中.假设指定路径为path,目标集合为fileList,遍 ...
- 总结java创建文件夹的4种方法及其优缺点-JAVA IO基础总结第三篇
本文是Java IO总结系列篇的第3篇,前篇的访问地址如下: 总结java中创建并写文件的5种方式-JAVA IO基础总结第一篇 总结java从文件中读取数据的6种方法-JAVA IO基础总结第二篇 ...
- java 资源文件的读取
Java将配置文件当作一种资源(resource)来处理,并且提供了两个类来读取这些资源,一个是Class类,另一个是ClassLoader类. gradle 项目 项目目录结构 用Class类加载 ...
- java中文件的读取和写入
//首先要顶一个file文件用来存放要读取的文件 File f=new File("c:/test/aa.txt"); //在实例化一个输入流,并把文件对象传到里面 FileInp ...
- java从文件中读取数据然后插入到数据库表中
实习工作中,完成了领导交给的任务,将搜集到的数据插入到数据库中,代码片段如下: static Connection getConnection() throws SQLException, IOExc ...
- Applet web端对文件的读取方式
转载:http://www.exam8.com/computer/Java/zonghe/200708/659876.html ---- 我们知道,在Java Applet中出于安全性考虑,Apple ...
- Java 对文件的读取操作
package pack; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; ...
- 多个yml文件的读取方式
1配置pom.xml文件,以下配置将默认激活-dev.yml配置文件<profiles> <profile> <id>dev&l ...
- Java—从文件中读取数据
1.FileInputStream() // 构建字节输入流对象,参数为文件名 FileInputStream fin = new FileInputStream("message" ...
随机推荐
- [转] .NET出现频率非常高的笔试题
又到了金三银四的跳槽季,许多朋友又开始跳槽了,这里我简单整理了一些出现频率比较高的.NET笔试题,希望对广大求职者有所帮助. 一..net基础 1. a=10,b=15,请在不使用第三方变量的情况下 ...
- JS实现最小生成树之普里姆(Prim)算法
最小生成树: 我们把构造连通网的最小代价生成树称为最小生成树.经典的算法有两种,普利姆算法和克鲁斯卡尔算法. 普里姆算法打印最小生成树: 先选择一个点,把该顶点的边加入数组,再按照权值最小的原则选边, ...
- Golang的 signal
在实际项目中我们可能有下面的需求: 1.修改了配置文件后,希望在不重启进程的情况下重新加载配置文件: 2.当用 Ctrl + C 强制关闭应用后,做一些必要的处理: 这时候就需要通过信号传递来进行处理 ...
- php 生成唯一id的几种解决方法(实例)
php 生成唯一id,网上查了下,有很多的方法 1.md5(time() . mt_rand(1,1000000)); 这种方法有一定的概率会出现重复 2.php内置函数uniqid() uniqid ...
- iview动态校验表单,获取值为undefined
场景:实际代码如下:https://run.iviewui.com/XPofr3YS 原因:在动态校验名称时,没法获取值,请教了大神后,发现原来是自己demo没理清楚 这里的prop="na ...
- Sql 列转行字符串
select OrderID,ProdDetailID from A 表A : OrderID,ProdDetailID 1 6 1 7 1 ...
- sql按中文数字排序
有表4张 建表和插入数据sql DECLARE @p_Building TABLE ( id INT , BidName ) ); DECLARE @p_Room TABLE ( id INT , R ...
- C语言四舍五入算法
对h进行四舍五入 1. 网络上搜索来的: C语言取整规则: (int)(h + 0.5) 2. 二级教程: 四舍五入并精确到小数点后面的第n位: 实例:
- RGB与INT类型的转换
开发时遇到的问题,设置图层样式时颜色的返回值是uint,一时不知改怎么转换为C#常用的RGB值了. 一番百度,结果如下: RGB = R + G * 256 + B * 256 * 256 因此可得到 ...
- 很赞的一个教程: React.js 小书
很赞, React.js 小书 http://huziketang.com/books/react/ 推荐阅读入门, 照着来一遍,能会个七七八八, 更多的还需要多写 import Re ...