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.
For example if I want to replace 3 words from the following:
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.
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
}
}
解决方案
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();
}
}