- 读取文件
- 正则匹配并替换括号中的内容为空
- 替换后的内容重新写入一个新的文件中
package com.company;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
/**
* @program: test
* @description: 去除文档中括号内的答案
* @author: Lzc
* @created: 2022/01/03 12:45
*/
public class test11 {
public static void main(String args[]) {
test11 te = new test11();
te.readfile();
}
public static String replacefile(String s){
// String s="5.在共产主义社会,成为乐生的活动,成为“生活的第一需要”的是( A ) ";
s=s.replaceAll("\\(.*?\\)|\\{.*?}|\\[.*?]|(.*?)", "( )");
System.out.println(s);
return s;
}
public void readfile(){
String filepath = "new.txt";
File file = new File(filepath);
BufferedReader reader = null;
try {
// System.out.println("以行为单位读取文件内容,一次读一整行:");
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
reader = new BufferedReader(isr);
// reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line :" + line );
String resultString = test11.replacefile(tempString);
test11.writefile(resultString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void writefile(String string){
//需要写入的文件的路径
String filePath = "马原题目(无答案版).txt";
try{
File file = new File(filePath);
FileOutputStream fos = null;
if(!file.exists()){
file.createNewFile();//如果文件不存在,就创建该文件
fos = new FileOutputStream(file);//首次写入获取
}else{
//如果文件已存在,那么就在文件末尾追加写入
fos = new FileOutputStream(file,true);//这里构造方法多了一个参数true,表示在文件末尾追加写入
}
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");//指定以UTF-8格式写入文件
osw.write(string);
//每写入一个Map就换一行
osw.write("\r\n");
osw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}