我正在尝试为这个问题编写一个程序:“编写一个程序,向用户询问字符串和文件名,然后从该文本文件中删除该字符串的所有出现。”
这是我到目前为止所拥有的:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class RemoveText {
public static void main(String[] args){
//creates a scanner to read the user's file name
Scanner input = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = input.nextLine();
java.io.File file = new java.io.File(fileName);
java.io.File newFile = new java.io.File(fileName);
Scanner stringToRemove = new Scanner(System.in);
System.out.println("Enter a string you wish to remove: ");
String s1 = stringToRemove.nextLine();
//creating input and output files
try {
Scanner inputFile = new Scanner(file);
//reads data from a file
while(inputFile.hasNext()) {
s1 += inputFile.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//supposed to replace each instance of the user input string
//but instead deletes everything on the file and i don't know why
String s2 = s1.replaceAll(s1, "");
try {
PrintWriter output = new PrintWriter(newFile);
output.write(s2);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//closing various scanners
input.close();
stringToRemove.close();
}
}
但由于某种原因,整个文本文件变成了空,而不是用空格替换字符串。我做错了什么?
编辑:好的,所以我听取了每个人的建议,并通过引入第三个字符串变量并使用更具描述性的变量名称来解决变量问题。
Scanner s1 = new Scanner(System.in);
String stringToRemove = s1.nextLine();
String fileContents = null;
try {
//stuff here
while (inputFile.hasNextLine()) {
fileContents += inputFile.nextLine();
} catch { //more stuff }
String outputContent = fileContents.replaceAll(stringToRemove, "");
我现在的问题是,在转发新内容之前,新文件的开头以“null”开头。
最佳答案
String s2 = s1.replaceAll(s1, "");
replaceAll方法的第一个参数是你要查找替换的内容,并且你正在寻找s1,你是说用这段代码清理所有s1内容...
关于java - 替换字符串会删除文本中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44378859/