简体   繁体   中英

Replacing a custom letter-special token combination with text in a File

What I'm trying to achieve is a program that will use a Template of a letter. In the template there will be text like

Hello Sir/Madam --NAME--

Is it somehow possible to replace the "--NAME--" with a customer.getName() method? I don't have any code yet but have been breaking my head over this problem.

Just read in the File. Then use Regex, or String.replace() or something else to just replace the --NAME-- with the name you want. It's really simple. EXAMPLE:

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

That's all you need

You can do it simply by using the Java - String replace() Method , here's what you need :

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

EDIT:

This code will save to another file, put it after the 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();

See the Reading, Writing, and Creating Files Java Doc for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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