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" ...
随机推荐
- Nginx proxy buffer相关的设置和解释
proxy_buffer_size 4k; proxy_buffering on;proxy_buffers 4 4k;proxy_busy_buffers_size 8k;proxy_max_tem ...
- html之内容解析
首先我们知道了HTML和css用途,那么今天就来看看HTML的一部分功能和用途. 简单的说HTML就是灵活使用标签,标签就相当于一个网页的骨架,有了这个骨架才能使网页更能区域色彩化. 首先来说HTML ...
- Vue学习笔记:Ref的使用
官网上的说明 1.了解Vue中的$refs在Vue中是怎么访问到DOM元素的 <div id="app"> <h1>{{ message }}</h1 ...
- GPUImage使用
GPUImage项目下载地址:https://github.com/BradLarson/GPUImage.git 下载项目时如果下载不下来可以直接check一份(之前下载了好多次都是下载失败,最后没 ...
- java poi处理新版xlsx后缀的excel
jar包下载地址http://poi.apache.org/download.html#POI-3.17,我把下载文件中的所有jar包都导入项目中才能跑 参考以下博客 https://www.cnbl ...
- log4j2配置文件
项目里面经常用到日志,Java开发一般用log4j.slf4j这些框架,看着配置文件有点懵.这几天看公司代码的时候,也有用到log4j,感觉要复杂一点.在本地打log,也有打到hive里面存的.看了一 ...
- spss C# 二次开发 学习笔记(四)——Spss授权
Spss的授权方式有两种,单机版和网络版. Spss的激活,在联网的情况下,通过20位的激活码激活,在未联网的情况下,Spss根据机器获取一个类似4-XXXX的锁定码,然后由激活码和锁定码算出一个授权 ...
- Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 不支持“variant”数据类型。
mybatis执行sqlserver的sql报错 com.microsoft.sqlserver.jdbc.SQLServerException: 不支持“variant”数据类型. at com.m ...
- GDAL读取影像并插值
影像读取 并缩放 读取大影像某一部分,并缩放到指定大小,我们有时会用如下代码: #include "gdal.h" #include "gdal_priv.h" ...
- Android版APM地面站,支持直连和数传台连接
现在隆重介绍APM上的手机/平板地面站 andropilot官方链接在此http://www.diydrones.com/groups/705844:Group:1132500?xg_source=m ...