[英]Storing A String From A Text Document And Printing It To The Screen
所以到目前為止,我有這段代碼:
import java.util.*;
import java.io.*;
public class EmailMerge {
public static void main(String[] args) throws IOException {
Scanner templateReader = null;
Scanner peopleReader = null;
PrintWriter out = null;
String template = "";
ArrayList people = new ArrayList();
try {
templateReader = new Scanner(new FileInputStream("template.txt"));
peopleReader = new Scanner(new FileInputStream("people.txt"));
while(templateReader.hasNext()) {
//System.out.print(templateReader.next());
template = templateReader.next();
}
System.out.println(template);
}
catch(FileNotFoundException e)
{
System.out.println("File(s) not found...");
System.exit(0);
}
}
}
我有一個名為template.txt的文本文檔,其中包含以下內容:
Dear <<N>>,
Because you are <<A>> years old and <<G>>, we have a
free gift for you. You have absolutely nothing to buy;
just pay the shipping and handling charge of $9.99. To
claim your gift, call us immediately.
Thank you,
Office of Claims Department
我還有一個名為people.txt的文本文檔,其中包含類似這樣的人的姓名和年齡:
John, 38, Male
Mary, 22, Female
so on and so forth...
我要做的是遍歷列表中的所有名稱,並使用模板制作個性化消息。 然后,我必須將每個文件保存到唯一的文本文檔(即John.txt)。 我想要做的是將列表中的名稱存儲到ArrayList中,我將其稱為people,然后將模板存儲至字符串中,並將其稱為template。
但是,當我嘗試打印模板時出現了我的問題。 我不能告訴我是否存儲錯誤,是否有更好的方法可以打印出來,但是當我使用此代碼時,我只是在屏幕上打印了“部門”。 我需要將整個內容存儲在String模板中,並能夠像上面一樣以適當的格式將其打印到屏幕上。 請幫助,謝謝一群!
更新:非常感謝你們的幫助! 還有一個問題。 我終於在項目的最后,並將所有必要的信息存儲在幾個ArrayList中,但是當我嘗試打印出模板時,它可以工作,但可以完成約1000次。 這是我正在使用的循環:
for(int j = 0; j < people.size(); j++){
for(int i = 0; i < names.size(); i++){
System.out.println(template.replace("<<N>>", names.get(i)).replace("<<A>>", ages.get(i)).replace("<<G>>", genders.get(i)));
}
}
我將所有名稱/年齡/性別存儲在適當的ArrayList中。 再次感謝!
您每次都替換模板 String變量,而不是對其進行更新(追加)。 請嘗試以下代碼:
template += templateReader.next();
或者更好-在評論由Luiggi說-一個StringBuilder
:
StringBuiler builder = new StringBuilder("");
while(templateReader.hasNext()) {
//System.out.print(templateReader.next());
builder.append(templateReader.next());
}
template = builder.toString();
StringBuffer
比+
運算符提供更好的性能 ,因此,每當您在循環中附加Strings
時(如本例所示),最好使用它。
使用StringBuilder將整個模板保存在String中:
StringBuilder sb = new StringBuilder();
while(templateReader.hasNext()){
//System.out.print(templateReader.next());
sb.append(templateReader.next());
}
template = sb.toString();
它比字符串連接快,尤其是在模板較長的情況下。
您可以使用一次全部讀取template.txt
String template = new Scanner(new File("template.txt")).useDelimiter("\\Z").next(); System.out.println(template);
useDelimiter(“ \\ Z”)用於一次讀取整個文件。
我建議將其分解為各個小部分,分別作為單獨的方法實現:
以這種方式設計代碼將使您能夠分別測試每個部分,並使跟蹤邏輯錯誤更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.