[英]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.