Java 用文件中的文本替换自定义字母特殊标记组合
我试图实现的是一个使用字母模板的程序。在模板中,将出现如下文本 您好,先生/女士,姓名--Java 用文件中的文本替换自定义字母特殊标记组合,java,file,replace,javafx,Java,File,Replace,Javafx,我试图实现的是一个使用字母模板的程序。在模板中,将出现如下文本 您好,先生/女士,姓名-- 是否有可能用customer.getName()方法替换“--NAME--”?我还没有任何代码,但一直在为这个问题绞尽脑汁 只要读入文件即可。然后使用Regex、String.replace()或其他方法将--NAME--替换为所需的名称。这真的很简单。 例如: BufferedReader in=new BufferedReader(new FileReader)(“”); StringBuilder=
是否有可能用
customer.getName()方法替换“--NAME--”
?我还没有任何代码,但一直在为这个问题绞尽脑汁 只要读入文件即可。然后使用Regex、String.replace()或其他方法将--NAME--替换为所需的名称。这真的很简单。
例如:
BufferedReader in=new BufferedReader(new FileReader)(“”);
StringBuilder=新的StringBuilder();
而((line=in.readLine())!=null)
{
builder.append(行);
}
in.close();
字符串yourText=builder.toString();
replace(“--NAME--”和“Testname”);
这就是您所需要的全部内容您只需使用即可,以下是您所需要的:
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();
有关更多信息,请参阅。不需要文件路径,因为它将准确地存储在代码看起来像X-Y问题的位置。您想要实现的是什么?将有一个名为“FileTemplate.txt”的文件f.e.在该文件中,将有一个标准模板,用于一个字母,其中包含类似于--NAME--的内容。我试图实现的是复制该文件,并通过customer.getName()将“-NAME--”替换为客户的名称。你可以这样做..寻找如何在文本文件中写入/更新特定位置。我尝试了这个方法,文件也在java代码所在的容器(Eclipse工作区)中。我在if(line.contains(“--NAME--”)中添加了System.out.println(“yes”)。它确实打印了yes。但是当我打开文件时,它没有更改内容。:/No,它不会写入文件。我会编辑我的答案,这样它就可以将新内容保存到另一个文件中。啊,我怎么会错过它呢!!我们必须编写line=line.replace(--NAME--)”文件,customer.getName());
而不是line.replace(“--NAME-”,customer.getName());
,它没有分配给文件变量,我将编辑我的答案。好的,我编辑了代码只需添加这一行newFile+=System.getProperty(“line.separator”);//添加一个新行
,它就会工作!更改String line=sc.next()
到字符串行=sc.nextLine();
就可以了。我编辑了我的答案。
//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();