Find and replace words in a text file using Java

Table of Contents

I am trying to find and replace certain words in a text file using Java. My code works to an extent however the output that 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 provided 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 } }

Source: Stack Overflow

Related Articles