Question

In: Computer Science

I need to write a java program (in eclipse) that will read my text file and...

I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries at once). If two people have the same name, create a new file by appending an index for the new file. For example, if there was another John in the second file, you will create John-1.txt for the new personalized letter. Assume that all the files that you read/write are in the same directory or the project build path of this class.

example template of text file:

Dear <N>,

You are <A> years old and <G>, we have a gift for you. You have absolutely nothing to buy; just pay the shipping and handling charge of $19.99.

To claim your gift, call us immediately.

Thank you!

Example information in second file:

John 22 male

Sara 32 female

John 45 male

Amy 21 female

Jim 60 male

example output of saved file:

Dear john,

You are 45 years old and male, we have a gift for you. You have absolutely nothing to buy; just pay the shipping and handling charge of $19.99.

To claim your gift, call us immediately.

Thank you!

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: The files containing template data and person data must be placed in the current working directory or the root directory of your project and when the program is executed, enter those names correctly. Failing to do this properly will cause FileNotFoundException. If that happens, check the file path/names and try again properly.

// ReplacePlaceholders.java

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.Scanner;

public class ReplacePlaceholders {

      // method to open a file, read the contents into a String variable and

      // return it

      static String readFile(File file) throws FileNotFoundException {

            Scanner scanner = new Scanner(file);

            String text = "";

            while (scanner.hasNext()) {

                  text += scanner.nextLine() + "\n";

            }

            scanner.close();

            return text.trim();

      }

      // method to save a text to a file with given name

      static void saveFile(String text, String name) throws FileNotFoundException {

            // creating a file object with name: name.txt

            File file = new File(name + ".txt");

            int i = 1;

            // looping as long as file exists

            while (file.exists()) {

                  // creating another file with index i

                  file = new File(name + "-" + i + ".txt");

                  i++;

            }

            // at this point, file does not exist, so we create a PrintWriter that

            // will create the required file a

            PrintWriter writer = new PrintWriter(file);

            // writing data

            writer.println(text);

            // closing file, saving changes

            writer.close();

      }

      public static void main(String[] args) throws FileNotFoundException {

            // scanner to read file names from keyboard

            Scanner scanner = new Scanner(System.in);

            // asking for first file name (containing template)

            System.out.print("Enter first file name: ");

            String filename = scanner.nextLine();

            File file1 = new File(filename);

            // reading contents of file1 to text

            String text = readFile(file1);

            // prompting for second file name

            System.out.print("Enter second file name: ");

            filename = scanner.nextLine();

            File file2 = new File(filename);

            // re initializing scanner to read from file2

            scanner = new Scanner(file2);

            // looping through each record in file2

            while (scanner.hasNext()) {

                  // copying text to a variable

                  String textForThisPerson = text;

                  // reading name, age and gender

                  String name = scanner.next();

                  int age = scanner.nextInt();

                  String gender = scanner.next();

                  // replacing placeholders with these values

                  textForThisPerson = textForThisPerson.replace("<N>", name);

                  textForThisPerson = textForThisPerson.replace("<A>", age + "");

                  textForThisPerson = textForThisPerson.replace("<G>", gender);

                  // saving updated data to file with name of the person

                  saveFile(textForThisPerson, name);

            }

            // closing file

            scanner.close();

      }

}

/*OUTPUT*/

Enter first file name: template.txt

Enter second file name: people.txt

/*screenshot of file structure after running the program*/



Related Solutions

Read a text file into arrays and output - Java Program ------------------------------------------------------------------------------ I need to have...
Read a text file into arrays and output - Java Program ------------------------------------------------------------------------------ I need to have a java program read an "input.txt" file (like below) and store the information in an respective arrays. This input.txt file will look like below and will be stored in the same directory as the java file. The top line of the text represents the number of people in the group for example. the lines below it each represent the respective persons preferences in regards...
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
Java - Text File to Arrays and output ------------------------------------------------------------------------------ I need to have a java program...
Java - Text File to Arrays and output ------------------------------------------------------------------------------ I need to have a java program read an "input.txt" file (like below) and store the information in an respective arrays. This input.txt file will look like below and will be stored in the same directory as the java file. The top line of the text represents the number of people in the group for example. the lines below it each represent the respective persons preferences in regards to the other...
Using java, I need to make a program that reverses a file. The program will read...
Using java, I need to make a program that reverses a file. The program will read the text file character by character, push the characters into a stack, then pop the characters into a new text file (with each character in revers order) EX: Hello World                       eyB       Bye            becomes    dlroW olleH I have the Stack and the Linked List part of this taken care of, I'm just having trouble connecting the stack and the text file together and...
Write a java program: Write a program that creates a text file. Write to the file...
Write a java program: Write a program that creates a text file. Write to the file three lines each line having a person's name. In the same program Append to the file one line of  'Kean University'.  In the same program then Read the file and print the four lines without lines between.
How do I do this: Write a program that can read a text file of numbers...
How do I do this: Write a program that can read a text file of numbers and calculate the mean and standard deviation of those numbers. Print the result in another text file. Put the result on the computer screen. EACH LINE OF THE PROGRAM MUST BE COMMENTED!
Write a C program to run on unix to read a text file and print it...
Write a C program to run on unix to read a text file and print it to the display. It should count of the number of words in the file, find the number of occurrences of a substring, and take all the words in the string and sort them (ASCII order). You must use getopt to parse the command line. There is no user input while this program is running. Usage: mywords [-cs] [-f substring] filename • The -c flag...
write a program in Java that can take a given text file and then compress it...
write a program in Java that can take a given text file and then compress it with Huffman coding due 20 october 2020 Huffman coding can be used to “zip” a text file to save space. You are required to write a program in Java that can take a given text file and then compress it with Huffman coding. Your program should be able to decompress the zipped files as well [4 marks]. In addition, show percentage gain in data...
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
Write a Java program to read a set of integers from a file, dataX, and a...
Write a Java program to read a set of integers from a file, dataX, and a set of ranges from a second file, rangeX, and, for each range [a, b] in rangeX, report the SUM of all the integers in dataX which are in the range [a, b]. As the integers are read from file dataX, insert them in a binary search tree. After all the integers have been inserted into the binary search tree, read the ranges from file...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT