简体   繁体   English

从文本文档中存储字符串并将其打印到屏幕

[英]Storing A String From A Text Document And Printing It To The Screen

So I have this code so far: 所以到目前为止,我有这段代码:

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

I have a text document called template.txt that contains this: 我有一个名为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

and I have another text document called people.txt that contains names and ages of people like so: 我还有一个名为people.txt的文本文档,其中包含类似这样的人的姓名和年龄:

John, 38, Male
Mary, 22, Female
so on and so forth...

What I have to do is go through all the names on the list and make a personalized message using the template. 我要做的是遍历列表中的所有名称,并使用模板制作个性化消息。 Then I have to save each to a unique text document(ie John.txt). 然后,我必须将每个文件保存到唯一的文本文档(即John.txt)。 What I want to do is store the names on the list into an ArrayList, I called people, and then store the template into a string, which I called template. 我想要做的是将列表中的名称存储到ArrayList中,我将其称为people,然后将模板存储至字符串中,并将其称为template。

However, my issue comes in when I try to print out the template. 但是,当我尝试打印模板时出现了我的问题。 I can't tell if I am storing it wrong of if there is a better way to print it out, but when I use this code I just get "Department" printed to the screen. 我不能告诉我是否存储错误,是否有更好的方法可以打印出来,但是当我使用此代码时,我只是在屏幕上打印了“部门”。 I need to have the whole thing stored in the String template and be able to print it to the screen in its proper format like it is above. 我需要将整个内容存储在String模板中,并能够像上面一样以适当的格式将其打印到屏幕上。 Please Help, Thanks A Bunch!! 请帮助,谢谢一群!

UPDATE: Thank you guys so much for the help! 更新:非常感谢你们的帮助! One more question. 还有一个问题。 I am finally at the end of the project and I have stored all of the necessary information into a few ArrayLists, however when I try to print out the template it will work, but it does it about a 1000 times. 我终于在项目的最后,并将所有必要的信息存储在几个ArrayList中,但是当我尝试打印出模板时,它可以工作,但可以完成约1000次。 Here is the loop I am using: 这是我正在使用的循环:

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

I stored all of the names/ages/genders into the appropriate ArrayList. 我将所有名称/年龄/性别存储在适当的ArrayList中。 Thanks again! 再次感谢!

You're replacing the template String variable each time instead of updating it (appending). 您每次都替换模板 String变量,而不是对其进行更新(追加)。 Try the code below: 请尝试以下代码:

template += templateReader.next();

Or better - as stated by Luiggi in the comment - a StringBuilder : 或者更好-在评论由Luiggi说-一个StringBuilder

StringBuiler builder = new StringBuilder("");
while(templateReader.hasNext()) {
        //System.out.print(templateReader.next());
        builder.append(templateReader.next());
}
template = builder.toString();

StringBuffer offers better performance than the + operator, so whenever you append Strings in a loop - like in this example - it's better to use it. StringBuffer+运算符提供更好的性能 ,因此,每当您在循环中附加Strings时(如本例所示),最好使用它。

Use a StringBuilder to save the whole template in a String : 使用StringBuilder将整个模板保存在String中:

StringBuilder sb = new StringBuilder();
while(templateReader.hasNext()){
    //System.out.print(templateReader.next());
    sb.append(templateReader.next());
}
template = sb.toString();

It is faster than String concatenation especially if your template is long. 它比字符串连接快,尤其是在模板较长的情况下。

You can read the template.txt all at once using 您可以使用一次全部读取template.txt

String template = new Scanner(new File("template.txt")).useDelimiter("\\Z").next();
    System.out.println(template);

useDelimiter("\\Z") is used to read whole file at once. useDelimiter(“ \\ Z”)用于一次读取整个文件。

I suggest breaking this into small parts that are each implemented as a separate method: 我建议将其分解为各个小部分,分别作为单独的方法实现:

  • One method to read in the file with the names and other data 一种读取文件名称和其他数据的方法
  • One method to read in the template 读入模板的一种方法
  • One method to replace the "fields" in the template with the correct data 一种用正确的数据替换模板中“字段”的方法

Designing your code this way will allow you to test each piece individually and make it easier to track down logic errors. 以这种方式设计代码将使您能够分别测试每个部分,并使跟踪逻辑错误更加容易。

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

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