0

I am trying to replace multiple strings in a file from source as ArrayList. But the application is erasing the old string before replacing a new one. Please help.

public static void writeNewFile(File template, ArrayList<String> data) {

    File file = template;
    String nameToReplace = "((name))";
    String productToReplace = "((product))";
    String giftToReplace = "((gift))";
    String giftValueToReplace = "((gift-value))";

    String outputFileName = data.get(0);

    String workingDirectory = System.getProperty("user.dir");

    Scanner scanner = null;

    try {
        scanner = new Scanner(file);
        PrintWriter writer = new PrintWriter(workingDirectory + "\\Output\\" + outputFileName);

        while (scanner.hasNextLine()) {
            String line1 = scanner.nextLine();
            writer.println(line1.replace(nameToReplace, data.get(1)));
            writer.println(line1.replace(productToReplace, data.get(2)));
        }
    } catch (Exception e) {
        System.out.println("Destination folder not found");
    }

}
rgettman
  • 176,041
  • 30
  • 275
  • 357
roj
  • 59
  • 4
  • Input? Expected output? Actual output? – Cardinal System May 18 '18 at 22:51
  • 1
    Don’t write each replacement separately, do all the replacing and then write the final result – MadProgrammer May 18 '18 at 22:52
  • What if value of `data.get(1)` is `"foo ((product)) bar"`? Should `((product))` be replaced by `data.get(1)`, i.e. should replacements cascade? If so, shouldn't they cascade both ways, e.g. if `data.get(2)` contains `((name))`, it should be replaced with `data.get(1)`? But if so, what if they are circular? --- To prevent cascading, you should consider an `appendReplacement` loop instead, e.g. see [How to replace multiple substring of a string at one time?](https://stackoverflow.com/q/38649267/5221149) – Andreas May 18 '18 at 23:02
  • yes, ((name)) should be replaced by data.get(1), ((product)) should be replaced by data.get(2) and so on – roj May 18 '18 at 23:11

1 Answers1

0

This worked for me

try {                   
                BufferedReader reader = new BufferedReader(new FileReader(file));
                String line = "", oldtext = "";
                while ((line = reader.readLine()) != null) {
                    oldtext += line + "\r\n";
                }
                reader.close();

                String result = oldtext.replace(nameToReplace, data.get(1))
                        .replace(productToReplace, data.get(2))
                        .replace(giftToReplace, data.get(3));

                // Write updated record to a file
                FileWriter writer = new FileWriter(workingDirectory + "\\Output\\" + outputFileName);
                writer.write(result);                
                writer.close();                
            } catch (IOException ioe) {
                System.out.println("Write error");
            }       
roj
  • 59
  • 4