使用java查找和替换文本文件中的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29056132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find and replace words in a text file using java
提问by JamesF
I am trying to find and replace certain words in a text file using java. My code works to an extent however the output I am getting is wrong. I need to replace multiple words from a line in a text file with user input however when I run my code the line copies itself once for every word I am trying to replace.
我正在尝试使用 java 在文本文件中查找和替换某些单词。我的代码在一定程度上有效,但是我得到的输出是错误的。我需要用用户输入替换文本文件中一行中的多个单词,但是当我运行我的代码时,该行为我尝试替换的每个单词复制一次。
For example if I want to replace 3 words from the following:
例如,如果我想替换以下 3 个单词:
python ycsb phase db -s -P /home/james/YCSB/workloads/workloada -p
db.url=db://IP:port -p db.database=name
I end up with 3 copies of the line, each with a different word replaced. Rather than 1 line with all 3 of the required words replaced. Code below, thanks in advance.
我最终得到了该行的 3 个副本,每个副本都替换了一个不同的单词。而不是 1 行替换了所有 3 个必需的单词。下面的代码,提前致谢。
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
}
}
采纳答案by Ricardo Umpierrez
if I understand well the situation, maybe the problem is that you are replacing the same string,and storing in different var,
如果我了解情况,也许问题在于您正在替换相同的字符串,并存储在不同的变量中,
try that:
试试看:
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();
}
}
回答by pavlos163
Even though I haven't written anything down so I haven't tested it, I think the problem is clearly seen in this part of the code:
尽管我没有写下任何东西所以我没有测试它,但我认为问题在这部分代码中很明显:
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);
You are creating 3 new strings. The first string has replaced phase, the second has replaced db and the third has replaced IP. That's clearly not what you want. You should do something like this:
您正在创建 3 个新字符串。第一个字符串替换了 phase,第二个替换了 db,第三个替换了 IP。这显然不是你想要的。你应该做这样的事情:
String phase = oldtext.replaceAll("phase", "" + p);
String database = phase.replaceAll("db", "" + d);
String ips = database.replaceAll("IP", "" + ip);
FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
writer.write(ips);
Edit: Oops, too late ^_^
编辑:哎呀,太晚了^_^
回答by Yeti
Better version of existing answers:
现有答案的更好版本:
public static void main(String[] args)
{
Scanner sp = new Scanner(System.in);
System.out.print("Phase: ");
String pstr = s.nextLine();
System.out.print("Database: ");
String dstr = s.nextLine();
System.out.print("IP address: ");
String ipstr = String.valueOf(s.nextInt());
After reading the input we can use two efficient methods to read from the file, and write back. First I suggest writing to a temporary file (this is how sed
replaces text in a file too). An advantage of this method is that the final move is probably going to be an atomic operation.
读取输入后,我们可以使用两种有效的方法从文件中读取并写回。首先,我建议写入一个临时文件(这也是sed
替换文件中文本的方式)。这种方法的一个优点是最后一步可能是一个原子操作。
File f = new File("C://users//James//Desktop//newcommand.txt");
File ftmp = new File("C://users//James//Desktop//~tmp.newcommand.txt", ".txt");
try
{
BufferedReader br = new BufferedReader(new FileReader(f));
BufferedWriter bw = new BufferedWriter(new FileWriter(ftmp));
String ln;
while((ln = br.readLine()) != null)
{
bw.write(ln
.replace("phase", pstr)
.replace("db", dstr)
.replace("IP", ipstr)
);
bw.newLine();
}
br.close();
bw.close();
Files.move(ftmp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e)
{
e.printStackTrace();
}
Or if you really don't want to have a temporary file, and thus keep everything in RAM, then use this code:
或者,如果您真的不想有一个临时文件,从而将所有内容都保存在 RAM 中,请使用以下代码:
File f = new File("C://users//James//Desktop//newcommand.txt");
try
{
String ENDL = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(f));
String ln;
while((ln = br.readLine()) != null)
{
sb.append(ln
.replace("phase", pstr)
.replace("db", dstr)
.replace("IP", ipstr)
).append(ENDL);
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(sb.toString());
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Don't forget the closing bracket ;)
不要忘记右括号;)
}
Note that - in contrary to the other answers - I am using .replace
instead of .replaceAll
. The only difference is that the latter interprets the first argument as a regular expression instead of a literal string. Both replace all occurrences, in this case there's no need for regular expressions and might only result in unwanted behavior due to special characters.
请注意 - 与其他答案相反 - 我正在使用.replace
而不是.replaceAll
. 唯一的区别是后者将第一个参数解释为正则表达式而不是文字字符串。两者都替换所有出现的,在这种情况下不需要正则表达式,并且可能只会由于特殊字符而导致不需要的行为。