gpt4 book ai didi

java - 使用 Java 查找和替换文本文件中的单词

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:40 26 4
gpt4 key购买 nike

我正在尝试使用 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
}
}

最佳答案

如果我很了解情况,也许问题是你正在替换相同的字符串,并存储在不同的 var 中,

试试看:

  public static void main(String[] args) {
System.out.print("Phase: ");
Scanner sp = new Scanner(System.in);
String p;
p = sp.nextLine();

System.out.print("Database: ");
Scanner sd = new Scanner(System.in);
String d;
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 replacedtext = oldtext.replaceAll("phase", "" + p);
replacedtext = replacedtext.replaceAll("db", "" + d);
replacedtext = replacedtext.replaceAll("IP", "" + ip);

FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
writer.write(replacedtext);


writer.close();

}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}

关于java - 使用 Java 查找和替换文本文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com