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 ...
随机推荐
- Confluence 6.15 使用附件宏
希望添加附件宏到一个页面中: 从编辑工具栏中,选择 插入(Insert) > 其他宏(Other Macros) 找到并且选择需要的宏. 可用使用自动完成加快这个过程:输入 { 然后开始输入 ...
- 7.6 T1 深度优先搜索(dfs)
深度优先搜索(dfs) [题目描述] sol:50pts随便写写,就是大众分了,直接n2dpOK,100分要找点规律,需要数学头脑 官方题解 //#include <bits/stdc++.h& ...
- Jmeter函数 参数
1.time时间函数 ${__time(,)} 1450056496991 //无格式化参数,返回当前毫秒时间 ${__time(/1000,)} //返回当前时间为秒 ${__time(yyyyMM ...
- 关于SpringBoot跨域的问题
直接在启动类里面加这一段代码就行: @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource sourc ...
- c# 调用CMD命令并获取输出结果
private static string CMDPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + " ...
- Nginx之监控进程和工作进程
1. 函数调用分析 在开启 master 的情况下,多进程模型的下的入口函数为 ngx_master_process_cycle,如下: int mian() { ... if (ngx_proces ...
- Alpha冲刺(2/6)
队名:007 组长博客: https://www.cnblogs.com/Linrrui/p/11861798.html 作业博客: https://edu.cnblogs.com/campus/fz ...
- Why are C# structs immutable?
Compiler Error CS1612 Cannot modify the return value of 'expression' because it is not a variable cl ...
- vue 指示点的疑点拓展
1. 为什么 vue 组件中的 data 是一个函数 1. 为了保证组件的独立性和可复用性,data 是一个函数,组件实例的时候,这个函数将会被调用,返回一个对象,计算机会给这个对象分配一个内存地址, ...
- [sh]shell语法小结
参考 基础语法 数字比较 -lt -eq -gt [ `ps -ef|grep nginx|grep -v grep|wc -l` -eq 0 ] str比较 == != [ $USER == &qu ...