替换文件java中的多个字符串

时间:2018-05-18 22:46:40

标签: java string arraylist io str-replace

我正在尝试将源文件中的多个字符串替换为ArrayList。但应用程序在更换新字符串之前擦除旧字符串。请帮忙。

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");
    }

}

1 个答案:

答案 0 :(得分:0)

这对我有用

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");
            }