Java文件读写分析
本文内容:IO流操作文件的细节分析;分析各种操作文件的方式。
读写一个文件
从一个示例开始分析,如何操作文件:
/**
* 向一个文件中写入数据
* @throws IOException
*/
private static void writeFile() throws IOException {
File file = new File("D://tmp/a.txt");
try (OutputStream outputStream = new FileOutputStream(file, false)) {
outputStream.write("ABC".getBytes(StandardCharsets.UTF_8));
}
}
/**
* 从一个文件中读取数据
* @throws IOException
*/
private static void readFile() throws IOException {
File file = new File("D://tmp/a.txt");
try (FileInputStream inputStream = new FileInputStream(file)) {
StringBuilder stringBuffer = new StringBuilder();
int count;
while ((count = inputStream.read()) != -1) {
stringBuffer.append((char) count);
}
System.out.println(stringBuffer.toString());
}
}
文件写入
向一个文件写入数据时,首先新建一个文件,然后定义一个输出流,为什么数输出流?Java里的API都是面向JVM的,输入和输出也是面向jvm的,输入就是向jvm中输入,输出就是从jvm中输出;
outputStream.write() 方法将一个字节数组写入到a.txt中,执行完该方法后文件中就有内容了。程序是如何写进去的?
/**
* Opens a file, with the specified name, for overwriting or appending.
* @param name name of file to be opened
* @param append whether the file is to be opened in append mode
*/
private native void open0(String name, boolean append)
throws FileNotFoundException;
/**
* Writes the specified byte to this file output stream.
*
* @param b the byte to be written.
* @param append {@code true} if the write operation first
* advances the position to the end of file
*/
private native void write(int b, boolean append) throws IOException;
/**
* Writes a sub array as a sequence of bytes.
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @param append {@code true} to first advance the position to the
* end of file
* @exception IOException If an I/O error has occurred.
*/
private native void writeBytes(byte b[], int off, int len, boolean append)
throws IOException;
private native void close0() throws IOException;
从源码上看,文件写入需要三个步骤:1、打开一个文件,也就是获取文件的句柄;2、向文件中输出字节流;3、关闭输出流,释放资源;
open0(String name, boolean append) 这个本地方法就是打开文件的方法,调用了操作系统的API。
write(int b, boolean append)这个本地方法是最终的写入的方法,参数有两个:b[],append; b代表的是一个字节数组,append代表是否添加,false则会覆盖初始文件。
文件读取
与写入文件类似,文件读取同样也是相对与jvm,文件读取是向jvm中输入,所以是InputStream;
private native int read0() throws IOException;
/**
* Reads a subarray as a sequence of bytes.
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @exception IOException If an I/O error has occurred.
*/
private native int readBytes(byte b[], int off, int len) throws IOException;
读取文件也是两种方法,一个字节一个字节地读,也能安装字节数组去读。步骤与文件写入类似:1、打开一个文件,也就是获取文件的句柄;2、从文件中读取字节流;3、关闭输入流,释放资源;
细节分析
字节数组读写的问题
按照字节写入,是直接调用native方法获取文件句柄操作文件,并且是直接写入字节数组,但是如果是写入中文,就不一样了,UTF-8编码中汉字是3个字节,英文字母是1个字节;当然不同的编码方式还不一样。这样写入不会有问题,但是读取的时候,问题就来了,汉字是3个字节,不管是按照字节数组还是字节去读,都可能只读取了一个汉字的一半,这样读取出来的字节数组转成可视化的内容就会出现乱码。
如果是从一个输入流到另外一个输出流,比如文件导出,就可以使用输入流读取的字节数组直接放到输出流中去。注意:读取到文件最后会返回-1,可以以此为分界点。
private static void writeFile0() throws IOException {
File fileA = new File("D://tmp/a.txt");
File fileB = new File("D://tmp/b.txt");
try (FileInputStream inputStream = new FileInputStream(fileA);
OutputStream outputStream = new FileOutputStream(fileB)) {
int count;
byte[] bytes = new byte[64];
while ((count = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, count);
}
}
}
按照字符读取
在Java API中提供了另外一种方式操作文件,那就是按照字符读取,也能按行读取。这种读取方式在文件和jvm中间加了一层缓冲区。
private static void readFile1() throws IOException {
File file = new File("D://tmp/a.txt");
try (FileReader fileReader = new FileReader(file)) {
BufferedReader bufferedReader = new BufferedReader(fileReader);
int count;
StringBuilder stringBuilder = new StringBuilder();
while ((count = bufferedReader.read()) != -1) {
// 还可以按行读取bufferedReader.readLine();
stringBuilder.append((char) count);
}
System.out.println(stringBuilder.toString());
}
}
Java文件读写分析的更多相关文章
- java 文件读写的有用工具
java 文件读写的有用工具 package org.rui.io.util; import java.io.BufferedReader; import java.io.File; import j ...
- java文件读写操作
Java IO系统里读写文件使用Reader和Writer两个抽象类,Reader中read()和close()方法都是抽象方法.Writer中 write(),flush()和close()方法为抽 ...
- java文件读写的两种方式
今天搞了下java文件的读写,自己也总结了一下,但是不全,只有两种方式,先直接看代码: public static void main(String[] args) throws IOExceptio ...
- java文件读写操作类
借鉴了项目以前的文件写入功能,实现了对文件读写操作的封装 仅仅需要在读写方法传入路径即可(可以是绝对或相对路径) 以后使用时,可以在此基础上改进,比如: 写操作: 1,对java GUI中文本框中的内 ...
- Java 文件读写操作
1[1]按字节读写,一次只读取一个字节,效率比较低 package bk1; import java.io.File; import java.io.FileInputStream; import j ...
- java文件读写操作指定编码格式
读文件: BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而提供字符.数组和行的高效读取. 可以指定缓冲区的大小,或者可使用默认的大小.大多数情况下,默认值就足够大了. 通常,R ...
- java文件读写工具类
依赖jar:commons-io.jar 1.写文件 // by FileUtilsList<String> lines = FileUtils.readLines(file, " ...
- java 文件读写demo
分析错误日志: import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public ...
- java 文件读写--转载
读文件 http://www.baeldung.com/java-read-file Java – Read from File 1. Overview In this tutorial we’ll ...
随机推荐
- The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online(2018 青岛网络预选赛)
A题 A Live Love 原题链接:https://pintia.cn/problem-sets/1036903825309761536/problems/1041155943483625472 ...
- 「Luogu P5603」小O与桌游
题目链接 戳我 \(Solution\) 我们来分析题目. 实际上就是求一个拓扑序满足拓扑序的前缀最大值最多/最少 对于第一种情况,很明显一直选当前能选的最小的是最优的对吧.因为你需要大的尽可能多.用 ...
- django-rest-framework之 json web token方式完成用户认证
json web token的介绍:https://blog.csdn.net/kevin_lcq/article/details/74846723 1. 安装 $ pip install djang ...
- legend3---lavarel安装debugbar工具条
legend3---lavarel安装debugbar工具条 一.总结 一句话总结: ` lavarel插件一般是composer官网下载,然后config/app.php中声明和加别名 ` 直接照官 ...
- (转)常用 HTTP 状态码对照表
Code 含义 100 客户端应当继续发送请求.这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝.客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应.服务器必须 ...
- 微信小程序之地址联动
这就是我们要实现的效果 <view class="consignee"> <!-- consignee 收件人 --> <text>收件人: & ...
- 离线安装nuget包EPPlus
1先去https://www.nuget.org/packages/EPPlus/4.1.0下载,epplus.4.1.0.nupkg 2找到本地文件位置:H:\DOWNLOAD\ 3在vs的程序包管 ...
- LC 274. H-Index
Given an array of citations (each citation is a non-negative integer) of a researcher, write a funct ...
- 服务安全-IAM:百科
ylbtech-服务安全-IAM:百科 IAM(身份识别与访问管理(简称大4A)) IAM(Identity and Access Management 的缩写),即“身份识别与访问管理”,具有单点登 ...
- 1、puppet基础
Puppet:IT基础设施自动化管理工具 参考文章: https://yq.aliyun.com/articles/120228 http://www.51niux.com/?id=105 http: ...