当前位置:网站首页>File read / write operation (files under the specified file directory)
File read / write operation (files under the specified file directory)
2022-07-22 09:39:00 【Go up the West building alone-】
File Introduction and reference of reading : https://blog.csdn.net/whjk20/article/details/114067986
The operation of writing is similar .
stay java In the actual reading and writing operation of the project , I found that if I only read and write by file name ( Use Files class ), Only read or write java root directory The files under the .
If you need to read And write Specify the directory Under the file , You need to use BufferedReader and BufferedWriter. The details are shown in the following code
It involves creating file directories File.mkdir /mkdirs , Get the files in the file directory File.listFiles, Relatively simple
Mainly 4-1 / 4-2 and 5-1 and 5-2 Function operation of . (4-2 and 5-2 Relatively flexible , You can batch operate files , And specify the directory , Easy to manage )
package com.example.javatest.fileoperation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FileDirReadWriteTest {
public static void main(String[] args) throws IOException {
System.out.println("---- main ----");
final String dirName = "InputFolder";
final String outDirName = "OutputFolder";
// 1. input dir & files
File inDir = new File(dirName);
if (!inDir.exists()) {
System.out.println("---- inDir not exist so create new dir ----");
inDir.mkdir();
} else {
System.out.println("---- inDir already exist ----");
}
System.out.println("---- final dir exist? " + inDir.getAbsolutePath());
File[] inFiles = inDir.listFiles();
System.out.println("---- inDir file size= " + inFiles.length);
// 2. output dir & files
System.out.println("---- outDir ----");
File outDir = new File(outDirName);
if (!outDir.exists()) {
System.out.println("---- outDir not exist so create new dir ----");
outDir.mkdirs();
} else {
System.out.println("---- outDir already exist ----");
}
System.out.println("---- final outDir exist? " + outDir.getAbsolutePath());
File[] outFiles = outDir.listFiles();
System.out.println("---- outFiles file size= " + outFiles.length);
// delete all output file
for (File f : outFiles) {
f.delete();
}
// 3. read input files and convert content, then write to output files
for (File f : inFiles) {
//List<String> texts = readLineFromFile(f.getName());
List<String> texts = readLineFromFile(f);
if (texts == null) {
System.out.println("---- no text in current input file so skip it");
continue;
}
List<String> convertedTexts = new ArrayList<>();
for (String text : texts) {
convertedTexts.add(text.toUpperCase());
}
//3-2 create related out file
File tmpFile = new File(outDir, "out2-" + f.getName());
if (!tmpFile.exists()) {
tmpFile.createNewFile();
}
//writeFile(f.getName(), convertedTexts);
writeFile(tmpFile, convertedTexts);
}
}
// 4. Read java Files in the root directory
private static List<String> readLineFromFile(String pathName) throws IOException {
System.out.println("---readLineFromFile pathName=" + pathName);
File file = new File(pathName);
if (!file.exists()) {
System.out.println("readLineFromFile file is not exist so return null ");
return null;
}
// TODO path It can only be read successfully under the project root directory , How to read if you want to read the specified directory ?
List<String> strings = Files.readAllLines(Paths.get(file.getName()), StandardCharsets.UTF_8);//Paths.get(pathName);
return strings;
}
//4-2 Read the specified file ( That is, in a specific directory ) The contents of the following documents
private static List<String> readLineFromFile(File file) throws IOException {
System.out.println("---readLineFromFile file name=" + file.getName());
if (!file.exists()) {
System.out.println("readLineFromFile file is not exist so return null ");
return null;
}
List<String> texts = new ArrayList<>();
InputStream inputStream = new FileInputStream(file);
if (inputStream == null) {
System.out.println("readLineFromFile inputStream is not null so return null ");
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
texts.add(line);
line = bufferedReader.readLine();
}
return texts;
}
// 5-1. According to the file name , Can only write java The root directory of the project
private static void writeFile(String fileName, List<String> texts) throws IOException {
System.out.println("---writeFile(String) fileName=" + fileName);
File file = new File("out-" + fileName);
if (!file.exists()) {
System.out.println("writeFile file is not exist and create new ");
file.createNewFile();
}
Files.write(Paths.get(file.getName()), texts, StandardCharsets.UTF_8);//Paths.get(pathName);
System.out.println("---writeFile successfully");
}
// 5-2 Write to the specified file ( That is, under the specified directory )
private static void writeFile(File file, List<String> texts) throws IOException {
System.out.println("---writeFile(File) fileName=" + file.getName());
if (!file.exists()) {
System.out.println("writeFile file is not exist and create new ");
file.createNewFile();
}
OutputStream outputStream = new FileOutputStream(file);
if (outputStream == null) {
System.out.println("writeFile outputStream is null so return ");
return;
}
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
if (texts == null) {
System.out.println("writeFile texts is null so write empty content ");
bufferedWriter.write("");
return;
}
StringBuilder stringBuilder = new StringBuilder();
int lineCount = texts.size();
for (int i = 0; i < lineCount; i++) {
stringBuilder.append(texts.get(i));
if (i != lineCount - 1) {
stringBuilder.append("\n");
}
}
bufferedWriter.write(stringBuilder.toString());
// need close, Otherwise, the write fails ( Not included )
bufferedWriter.close();
System.out.println("---writeFile successfully");
}
}
边栏推荐
猜你喜欢
关于线程 thread (4)线程的交互
关于线程 thread (5)线程池
排序方法:冒泡排序(使用数组实现一串数字的顺序排列(从大到小或从小到大))
排序方法--冒泡排序(使用数组实现一串数字的从大到小或从小到大排序)
20201127 使用Markdown 画uml图,Graphviz 安装经历吐血整理
[original] principle of an automatic nine point calibration tool (including part of the source code)
高频leetcode深搜部分:98. 验证二叉搜索树
office2016—word不能使用输入法,只能输入英文问题
Programmers' wisdom and courage in those years!!!
andorid 查看 Activity任务栈
随机推荐
High frequency leetcode deep search part: 124 Maximum path sum in binary tree
EAS BOS 报表开发
High frequency leetcode deep search part: Sword finger offer 13 Range of motion of robot
高频leetcode深搜部分:617. 合并二叉树
electron
EAS Web BIM Start Access prompt 500 Error
力扣题之整数反转
2022年 iuap 春季培训数据中台培训报道
[original] principle of an automatic nine point calibration tool (including part of the source code)
嵌入式问题排查手段、网络问题、SD卡问题、设备启动问题、串口问题、i2c问题、spi问题、pcie等等问题
EAS Web BIM啟動訪問提示500錯誤
开发环境 EAS登录 license 许可修改
嵌入式之SD卡/U盘只读问题解决方案(FAT只读修复方式)
排序方法:冒泡排序(使用数组实现一串数字的顺序排列(从大到小或从小到大))
数据治理质量保障研究
Development environment EAS login license modification
第十题:在行和列都排好序的数组中找数
High frequency leetcode deep search part: 695 Maximum area of the island
NProgress
SwipeMenuRecyclerView 的用法