File 读的介绍参考: https://blog.csdn.net/whjk20/article/details/114067986
写的操作类似。
在java工程实际读写操作中,发现如果仅按文件名去读写 (使用Files 类), 只能读取或者写入 java 根目录下的文件。
如果需要读取 和写入 指定目录下的文件,则需要使用 BufferedReader 和 BufferedWriter。 具体如下代码所示
其中涉及创建文件目录 File.mkdir /mkdirs , 获取文件目录下的文件 File.listFiles, 相对简单
主要是 4-1 / 4-2 和 5-1和5-2的函数操作。 (4-2 和 5-2 相对灵活,可以对文件批量操作,并且指定目录,方便管理)
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. 读取java根目录下的文件
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 在项目根目录下才能读取成功,如果要读取指定目录的该如何读取?
List<String> strings = Files.readAllLines(Paths.get(file.getName()), StandardCharsets.UTF_8);//Paths.get(pathName);
return strings;
}
//4-2 读取指定文件(即在特定目录)下的文件内容
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. 根据文件名,只能写java项目的根目录下
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 写入到指定的文件(即指定目录下)
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());
//需要close, 否则写失败(没有写进内容)
bufferedWriter.close();
System.out.println("---writeFile successfully");
}
}