繁体   English   中英

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

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

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

您好先生/女士--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()方法即可完成此操作 ,这是您需要的:

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();

有关更多信息请参见读取,写入和创建文件Java Doc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM