【发布时间】:2015-03-15 01:08:07
【问题描述】:
我正在尝试使用 Java 查找和替换文本文件中的某些单词。我的代码在一定程度上有效,但是我得到的输出是错误的。 我需要用用户输入替换文本文件中一行中的多个单词。但是,当我运行我的代码时,该行会为我尝试替换的每个单词复制一次。
例如,如果我想替换以下 3 个单词:
python ycsb phase db -s -P /home/james/YCSB/workloads/workloada -p
db.url=db://IP:port -p db.database=name
我最终得到了 3 个副本,每个副本都替换了一个不同的单词。而不是替换所有 3 个必需单词的 1 行。 下面提供了代码,在此先感谢。
public static void main(String[] args) {
System.out.print("Phase: ");
Scanner sp = new Scanner(System.in);
String p = sp.nextLine();
System.out.print("Database: ");
Scanner sd = new Scanner(System.in);
String d = sd.nextLine();
System.out.print("IP address: ");
Scanner sip = new Scanner(System.in);
int ip = sip.nextInt();
try {
File file = new File("C://users//James//Desktop//newcommand.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String phase = oldtext.replaceAll("phase", "" + p);
String database = oldtext.replaceAll("db", "" + d);
String ips = oldtext.replaceAll("IP", "" + ip);
FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
writer.write(phase + ips + database);
writer.close();
} catch (IOException e) {
// handle e
}
}
【问题讨论】:
标签: java