修改文件内容并输出
引入依赖包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
快速读取文件内容
IOUtils.toString(fileInputStream, "UTF-8")
处理目标文本内容,并输出到指定目录
package com.qiankai.io;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.Scanner;
/**
* IOUtils 文件操作Demo
*
* @author kai_qian
* @version v1.0
* @since 2020/08/04 14:51
*/
public class FileMain {
public static void main(String[] args) throws IOException {
String filePath;
String targetPath = "D:\\Users\\Desktop\\b.txt";
Scanner scanner = new Scanner(System.in);
System.out.println("===========================================================");
System.out.println("----------请输入文件目录:" + "-------------------------------");
filePath = scanner.next();
while (!"end".equals(filePath)) {
String oriContext = readFileToString(filePath);
String targetContext = handle(oriContext);
outputToFile(targetContext, targetPath);
System.out.println("----------输出到:" + targetPath + "------------------------");
System.out.println("===========================================================");
System.out.println("----------请输入文件目录(输入 ‘end’ 退出):" + "----------------");
filePath = scanner.next();
}
}
/**
* 将内容输出到文件
*
* @param context 要写入文件的内容
* @param path 输出文件的位置
*/
public static void outputToFile(String context, String path) {
try {
InputStream inputStream = IOUtils.toInputStream(context, "UTF-8");
OutputStream outputStream = new FileOutputStream(new File(path));
// 输出文件
IOUtils.copy(inputStream, outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 具体的处理逻辑
* @param context
* @return
*/
private static String handle(String context) {
// 自定义处理逻辑
context = context.replaceAll("aa", "bb");
return context;
}
/**
* 读取文件内容
*
* @param filePath 文件路径
* @return 字符串
*/
private static String readFileToString(String filePath) {
try {
// 读取文件内容
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
return IOUtils.toString(fis, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
// private static boolean patternMatch(String context, String pattern) {
// Pattern p = Pattern.compile(pattern);
// Matcher matcher = p.matcher(context);
// if (matcher.find()) {
// // matcher.group(0);
// return true;
// }
// System.out.println("NOT MATCH");
// return false;
// }
}