【发布时间】:2020-11-01 12:56:57
【问题描述】:
我试图实现一个简单的程序来从文件中删除特定文本,但它无法删除它。我正在将整个文件内容读入临时文件,从中删除用户输入字符串并将内容更新为原始文件。 任何帮助将不胜感激。
public class TextEraser{
public static void main(String[] args) throws IOException {
System.out.print("Enter a string to remove : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
// Locate the file
File file = new File("/Users/lobsang/documents/input.txt");
//create temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
String s = in.readLine();
// Read each line from the file and echo it to the screen.
while (s !=null) {
s=s.replace(inputString,"");
s = in.readLine();
}
writer.println(s);
// Close the buffered reader
in.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
}
}
【问题讨论】:
-
您将输入字符串替换为空字符串,可以,并将其存储到
s。然后你阅读下一行并再次覆盖s。你没有对被替换的行做任何事情。您需要将替换后的字符串写入输出文件,因此请在s=s.replace(inputString,"");之后添加一行。 -
所以我相信 s=s.replace(inputstring,"")。 - 如果用户输入字符串在该行中,则将其替换为空字符串...然后最后我将该行写入带有 writer.println(s) 的临时文件..我是否缺少某些东西...可以你请给我更多的细节..很失落
标签: java file java.util.scanner filereader