Java读写文件常用方法
一.字符流:读写纯文本(txt,csv等),
1 字符流写文件主要用:FileWriter,BufferedWriter,PrintWriter
1.1 测试 FileWriter 写入
private void writeFileWriter() throws IOException {
try (FileWriter fw = new FileWriter(basicPath + "writeUnicode_FileWriter.txt")) {
fw.write("测试 FileWriter 写入。");
}
}
1.2 测试 BufferedWriter 写入
private void writeBufferedWriter() throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(basicPath + "writeUnicode_BufferedWriter.txt"))) {
bw.write("测试 BufferedWriter 写入。");
}
}
1.3 测试 PrintWriter 写入
private void writePrintWriter() throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter(basicPath + "writeUnicode_PrintWriter.txt"))) {
pw.write("测试 PrintWriter 写入。");
}
}
2 字符流读文件主要用:FileReader,BufferedReader
2.1 测试 FileReader 读取
private void readFileReader() throws IOException {
// 方式1:一个一个char读取 (不推荐)
try (FileReader fr = new FileReader(basicPath + "writeUnicode_FileWriter.txt")) {
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
}
// 方式2:数组自定长度一次性读取
try (FileReader fr = new FileReader(basicPath + "writeUnicode_FileWriter.txt")) {
char[] buf = new char[1024];
int length;
while ((length = fr.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
}
2.2测试 BufferedReader 读取
private void readBufferedReader() throws IOException {
// 方式1:一个一个char读取 (不推荐)
try (BufferedReader br = new BufferedReader(new FileReader(basicPath + "writeUnicode_BufferedWriter.txt"))) {
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
}
// 方式2:数组自定长度一次性读取
try (BufferedReader br = new BufferedReader(new FileReader(basicPath + "writeUnicode_BufferedWriter.txt"))) {
char[] buf = new char[1024];
int length;
while ((length = br.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
// 方式3:bufferedReader.readLine()读取
try (BufferedReader br = new BufferedReader(new FileReader(basicPath + "writeUnicode_BufferedWriter.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.print(line);
}
}
}
二.字节流:读取视频,音频,二进制文件等,(文本文件也可以但不推荐,以下仅为测试用)
1 字节流写文件主要用:FileOutputStream,BufferedOutputStream
1.1 测试 FileOutputStream 写入
private void writeFileOutputStream() throws IOException {
try (FileOutputStream fos = new FileOutputStream(basicPath + "writeByte_FileOutputStream.txt")) {
String content = "测试 FileOutputStream 写入。";
byte[] bytes = content.getBytes();
fos.write(bytes);
}
}
1.2 测试 BufferedOutputStream 写入
private void writeBufferedOutputStream() throws IOException {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(basicPath + "writeByte_BufferedOutputStream.txt"))) {
String content = "测试 BufferedOutputStream 写入。";
byte[] bytes = content.getBytes();
bos.write(bytes);
}
}
2 字节流读文件主要用:FileInputStream,BufferedInputStream
2.1 测试 FileInputStream 读取
private void readFileInputStream() throws IOException {
// 方式1:一个一个char读取 (不推荐,且中文占2个字节,此方式读中文文件会造成乱码)
try (FileInputStream fis = new FileInputStream(basicPath + "writeByte_FileOutputStream.txt")) {
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
}
// 方式2:数组自定长度一次性读取
try (FileInputStream fis = new FileInputStream(basicPath + "writeByte_FileOutputStream.txt")) {
byte[] buf = new byte[1024];
int length;
while ((length = fis.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
}
2.2 测试 BufferedInputStream 读取
private void readBufferedInputStream() throws IOException {
// 方式1:一个一个char读取 (不推荐,且中文占2个字节,此方式读中文文件会造成乱码)
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basicPath + "writeByte_BufferedOutputStream.txt"))) {
int c;
while ((c = bis.read()) != -1) {
System.out.print((char) c);
}
}
// 方式2:数组自定长度一次性读取
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basicPath + "writeByte_BufferedOutputStream.txt"))) {
byte[] buf = new byte[1024];
int length;
while ((length = bis.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
}
三.通过 Files类读写文件
1 测试 Files类写入
private void writeFiles() throws IOException {
String content = "测试 Files 类写入。\n第二行";
Files.write(Paths.get(basicPath + "writeFiles.txt"), content.getBytes());
}
2 测试 Files类读取
private void readFiles() throws IOException {
// 方式1 (文件特大时会占满内存)
byte[] bytes = Files.readAllBytes(Paths.get(basicPath + "writeFiles.txt"));
String srcStr1 = new String(bytes);
System.out.println(srcStr1);
// 方式2 (文件特大时会占满内存)
List<String> lines = Files.readAllLines(Paths.get(basicPath + "writeFiles.txt"));
StringBuilder sb = new StringBuilder();
for (String line : lines) {
// 此时line最后没有换行,因为readAllLines以换行分隔了所有行,可以用System.out.print 看到效果
sb.append(line).append("\n");
}
String srcStr2 = sb.toString();
System.out.println(srcStr2);
// 方式3 JDK8的Stream流,边消费边读取
String srcStr3 = Files.lines(Paths.get(basicPath + "writeFiles.txt")).reduce((s1, s2) -> s1 + s2).get();
System.out.println(srcStr3);
}
四.源码
1 字符流读写

package com.writefiles; import java.io.*; /**
* @author: Convict.Yellow
* @date: 2020/12/22 16:11
* @description: 字符流的基本单位为 Unicode,大小为两个字节(Byte),主要用来处理文本数据。
* 字符流有两个基类:Reader(输入字符流)和 Writer(输出字符流)。
* <p>
* 字符流写文件主要用:FileWriter,BufferedWriter,PrintWriter
* 字符流读文件主要用:FileReader,BufferedReader
*/
public class WriteAndReadByUnicode { private static final String basicPath = "D:/ztest/"; public static void main(String[] args) throws IOException {
WriteAndReadByUnicode entrance = new WriteAndReadByUnicode(); // 测试 FileWriter 写入
entrance.writeFileWriter();
// 测试 BufferedWriter 写入
entrance.writeBufferedWriter();
// 测试 PrintWriter 写入
entrance.writePrintWriter(); // 测试 FileReader 读取
entrance.readFileReader();
// 测试 BufferedReader 读取
entrance.readBufferedReader();
} private void writeFileWriter() throws IOException {
try (FileWriter fw = new FileWriter(basicPath + "writeUnicode_FileWriter.txt")) {
fw.write("测试 FileWriter 写入。");
}
} private void writeBufferedWriter() throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(basicPath + "writeUnicode_BufferedWriter.txt"))) {
bw.write("测试 BufferedWriter 写入。");
}
} private void writePrintWriter() throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter(basicPath + "writeUnicode_PrintWriter.txt"))) {
pw.write("测试 PrintWriter 写入。");
}
} private void readFileReader() throws IOException {
// 方式1:一个一个char读取 (不推荐)
try (FileReader fr = new FileReader(basicPath + "writeUnicode_FileWriter.txt")) {
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
} // 方式2:数组自定长度一次性读取
try (FileReader fr = new FileReader(basicPath + "writeUnicode_FileWriter.txt")) {
char[] buf = new char[1024];
int length;
while ((length = fr.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
} private void readBufferedReader() throws IOException {
// 方式1:一个一个char读取 (不推荐)
try (BufferedReader br = new BufferedReader(new FileReader(basicPath + "writeUnicode_BufferedWriter.txt"))) {
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
} // 方式2:数组自定长度一次性读取
try (BufferedReader br = new BufferedReader(new FileReader(basicPath + "writeUnicode_BufferedWriter.txt"))) {
char[] buf = new char[1024];
int length;
while ((length = br.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
} // 方式3:bufferedReader.readLine()读取
try (BufferedReader br = new BufferedReader(new FileReader(basicPath + "writeUnicode_BufferedWriter.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.print(line);
}
}
} }
2 字节流读写

package com.writefiles; import java.io.*; /**
* @author: Convict.Yellow
* @date: 2020/12/22 15:27
* @description: 字节流的基本单位为字节(Byte),一个字节为8位(bit),主要是用来处理二进制(数据)。
* 字节流有两个基类:InputStream(输入字节流)和 OutputStream(输出字节流)。
* <p>
* 字节流写文件主要用:FileOutputStream,BufferedOutputStream
* 字节流读文件主要用:FileInputStream,BufferedInputStream
*/
public class WriteAndReadByByte { private static final String basicPath = "D:/ztest/"; public static void main(String[] args) throws IOException {
WriteAndReadByByte entrance = new WriteAndReadByByte(); // 测试 FileOutputStream 写入
entrance.writeFileOutputStream();
// 测试 BufferedOutputStream 写入
entrance.writeBufferedOutputStream(); // 测试 FileInputStream 读取
entrance.readFileInputStream();
// 测试 BufferedInputStream 读取
entrance.readBufferedInputStream(); } private void writeFileOutputStream() throws IOException {
try (FileOutputStream fos = new FileOutputStream(basicPath + "writeByte_FileOutputStream.txt")) {
String content = "测试 FileOutputStream 写入。";
byte[] bytes = content.getBytes();
fos.write(bytes);
}
} private void writeBufferedOutputStream() throws IOException {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(basicPath + "writeByte_BufferedOutputStream.txt"))) {
String content = "测试 BufferedOutputStream 写入。";
byte[] bytes = content.getBytes();
bos.write(bytes);
}
} private void readFileInputStream() throws IOException {
// 方式1:一个一个char读取 (不推荐,且中文占2个字节,此方式读中文文件会造成乱码)
try (FileInputStream fis = new FileInputStream(basicPath + "writeByte_FileOutputStream.txt")) {
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
} // 方式2:数组自定长度一次性读取
try (FileInputStream fis = new FileInputStream(basicPath + "writeByte_FileOutputStream.txt")) {
byte[] buf = new byte[1024];
int length;
while ((length = fis.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
} private void readBufferedInputStream() throws IOException {
// 方式1:一个一个char读取 (不推荐,且中文占2个字节,此方式读中文文件会造成乱码)
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basicPath + "writeByte_BufferedOutputStream.txt"))) {
int c;
while ((c = bis.read()) != -1) {
System.out.print((char) c);
}
} // 方式2:数组自定长度一次性读取
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basicPath + "writeByte_BufferedOutputStream.txt"))) {
byte[] buf = new byte[1024];
int length;
while ((length = bis.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
} }
3 Files类读写

package com.writefiles; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List; /**
* @author: Convict.Yellow
* @date: 2020/12/22 16:11
* @description:
*
*/
public class WriteAndReadByFiles { private static final String basicPath = "D:/ztest/"; public static void main(String[] args) throws IOException {
WriteAndReadByFiles entrance = new WriteAndReadByFiles(); // 测试 Files类写入
entrance.writeFiles(); // 测试 Files类读取
entrance.readFiles();
} private void writeFiles() throws IOException {
String content = "测试 Files 类写入。\n第二行";
Files.write(Paths.get(basicPath + "writeFiles.txt"), content.getBytes());
} private void readFiles() throws IOException {
// 方式1 (文件特大时会占满内存)
byte[] bytes = Files.readAllBytes(Paths.get(basicPath + "writeFiles.txt"));
String srcStr1 = new String(bytes);
System.out.println(srcStr1); // 方式2 (文件特大时会占满内存)
List<String> lines = Files.readAllLines(Paths.get(basicPath + "writeFiles.txt"));
StringBuilder sb = new StringBuilder();
for (String line : lines) {
// 此时line最后没有换行,因为readAllLines以换行分隔了所有行,可以用System.out.print 看到效果
sb.append(line).append("\n");
}
String srcStr2 = sb.toString();
System.out.println(srcStr2); // 方式3 JDK8的Stream流,边消费边读取
String srcStr3 = Files.lines(Paths.get(basicPath + "writeFiles.txt")).reduce((s1, s2) -> s1 + s2).get();
System.out.println(srcStr3);
} }
Tip:均采用 try-with-resources写法,故无需手动 close流,try-with-resources写法可参考此处。
Java读写文件常用方法的更多相关文章
- java 读写文件常用方法
package study.bigdata; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; ...
- Java读写文件方法总结
Java读写文件方法总结 Java的读写文件方法在工作中相信有很多的用处的,本人在之前包括现在都在使用Java的读写文件方法来处理数据方面的输入输出,确实很方便.奈何我的记性实在是叫人着急,很多时候既 ...
- Java读写文件的几种方式
自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...
- java读写文件大全
java读写文件大全 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(char[] ch,int o ...
- 【java】java 读写文件
场景:JDK8 将上传的文件,保存到服务器 Java读写文件操作: MultipartFile file InputStream inputStream = file.getInputStream( ...
- 转:Java读写文件各种方法及性能比较
干Java这么久,一直在做WEB相关的项目,一些基础类差不多都已经忘记.经常想得捡起,但总是因为一些原因,不能如愿. 其实不是没有时间,只是有些时候疲于总结,今得空,下定决心将丢掉的都给捡起来. 文件 ...
- 161012、JAVA读写文件,如何避免中文乱码
1.JAVA读取文件,避免中文乱码. /** * 读取文件内容 * * @param filePathAndName * String 如 c:\\1.txt 绝对路径 * @return boole ...
- java 读写文件乱码问题
这样写,会出现乱码.原因是文件时gbk格式的, BufferedReader br = new BufferedReader(new FileReader(indir)); BufferedWrite ...
- java读写文件小心缓存数组
一般我们读写文件的时候都是这么写的,看着没问题哈. public static void main(String[] args) throws Exception { FileInputStr ...
随机推荐
- org.reflections 接口通过反射获取实现类源码研究
org.reflections 接口通过反射获取实现类源码研究 版本 org.reflections reflections 0.9.12 Reflections通过扫描classpath,索引元数据 ...
- linux(CentOS7) 之 MySQL 5.7.30 下载及安装
一.下载 1.百度搜索mysql,进入官网(或直接进入官网https://www.mysql.com) 2.选择 downloads 3.翻到最下面,选择MySQL Community (GPL) D ...
- Python调用aiohttp
1. aiohttp安装 pip install aiohttp 1.1. 基本请求用法 async with aiohttp.get('https://github.com') as r: awai ...
- Word2010制作自动目录
原文链接:https://www.toutiao.com/i6488296610873737741/ 原文从网上复制: 查看"开始"选项卡,"样式"功能组,我们 ...
- Go的WaitGroup源码分析
WaitGroup 是开发中经常用到的并发控制手段,其源代码在 src/sync/waitgroup.go 文件中,定义了 1 个结构体和 4 个方法: WaitGroup{}:结构体. state( ...
- JVM调优工具锦囊
Arthas线上 分析诊断调优工具 以前我们要排查线上问题,通常使用的是jdk自带的调优工具和命令.最常见的就是dump线上日志,然后下载到本地,导入到jvisualvm工具中.这样操作有诸多不变,现 ...
- 开启mysql外部访问(root外连)
MySQL外部访问 mysql 默认是禁止远程连接的,你在安装mysql的系统行运行mysql -u root -p 后进入mysql 输入如下: mysql>use mysql; mysql& ...
- 《剑指offer》面试题56 - II. 数组中数字出现的次数 II
问题描述 在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次.请找出那个只出现一次的数字. 示例 1: 输入:nums = [3,4,3,3] 输出:4 示例 2: 输入:nums ...
- Solon Web 开发,四、请求上下文
Solon Web 开发 一.开始 二.开发知识准备 三.打包与运行 四.请求上下文 五.数据访问.事务与缓存应用 六.过滤器.处理.拦截器 七.视图模板与Mvc注解 八.校验.及定制与扩展 九.跨域 ...
- 【刷题-LeetCode】238. Product of Array Except Self
Product of Array Except Self Given an array nums of n integers where n > 1, return an array outpu ...