用文件中的文本替换自定义字母特殊标记组合

Replacing a custom letter-special token combination with text in a File

我想要实现的是一个将使用字母模板的程序。在模板中会有类似

的文本

Hello Sir/Madam --NAME--

是否可以用 customer.getName() 方法替换 "--NAME--"?我还没有任何代码,但一直在为这个问题而烦恼。

刚刚读入文件。然后使用 Regex 或 String.replace() 或其他方式将 --NAME-- 替换为您想要的名称。这真的很简单。 示例:

BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
StringBuilder builder = new StringBuilder();
while((line = in.readLine()) != null)
{
    builder.append(line);
}
in.close();
String yourText = builder.toString();
yourText.replace("--NAME--", "Testname");

这就是你所需要的

您只需使用 Java - String replace() Method 即可完成,这就是您所需要的:

File file = new File("FileTemplate.txt");
String newFile="";
try {
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        if(line.contains("--NAME--")){
                line = line.replace("--NAME--", customer.getName()); 
        }
        newFile+=line;
        newFile+=System.getProperty("line.separator"); // add a newLine 
    }
    sc.close();
} 
catch (FileNotFoundException e) {
    e.printStackTrace();
}

编辑:

这段代码将保存到另一个文件中,放在try/catch:

之后
       //Create an new File with the customer name
       File file2 = new File(customer.getName()+".txt"); //make sure you enter the right path
        if (!file2.exists()) {
            file2.createNewFile(); //create the file if it doesn't exist
        }

        FileWriter fw = new FileWriter(file2.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(newFile); // write the new Content to our new file 
        bw.close();

有关详细信息,请参阅 Reading, Writing, and Creating Files Java Doc