上面是一个工作代码段。该代码运行良好,但未编写该else if(line.contains("{NEW_LIMIT}"))语句中的内容。另一个问题是,程序在写入新文本文件后会丢失其原始格式,也就是说,它只是将所有内容写在一行中。我做错了什么吗?public static void replace1(String name, String limit, String nlimit) throws IOException{ File infile = new File("s://BlackBuck/Question_1_Template.txt"); File outfile = fileReturn(); FileWriter fw; BufferedWriter bw = null; FileReader fr; BufferedReader br = null; String line, putdata = null;; try { fr = new FileReader(infile); br = new BufferedReader(fr); fw = new FileWriter(outfile); bw = new BufferedWriter(fw); while((line = br.readLine()) != null) { if(line != null) { if(line.contains("{CUSTOMER_NAME}")) { putdata = line.replace("{CUSTOMER_NAME}", name); bw.write(putdata); } else if(line.contains("{CURRENT_LIMIT}")) { putdata = line.replace("{CURRENT_LIMIT}", limit); bw.write(putdata); } else if(line.contains("{NEW_LIMIT}")) { putdata = line.replace("{NEW_LIMIT}", nlimit); bw.write(putdata); } else { bw.write(line); } } } }finally { bw.close(); br.close(); }}
1 回答
慕斯709654
TA贡献1840条经验 获得超5个赞
如果一行包含{CUSTOMER_NAME}或{CURRENT_LIMIT},则语句{NEW_LIMIT}将不会运行。您可以使用以下代码简单地解决此问题:
if(line != null) {
putdata = line.replace("{CUSTOMER_NAME}", name)
.replace("{CURRENT_LIMIT}", limit)
.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
// append a line separator to current line
bw.newLine();
}
添加回答
举报
0/150
提交
取消