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

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.
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...
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!
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...
In JAVA Write a brief program that writes your name to a file in text format...
In JAVA Write a brief program that writes your name to a file in text format and then reads it back. Use the PrintWriter and Scanner classes.
JAVA Assignment: Project File Processing. Write a program that will read in from input file one...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of...
Write a program that computes and prints the average of numbers in a text file. I...
Write a program that computes and prints the average of numbers in a text file. I created a text file integers.txt that has the numbers 5,4,3,2,1. I need to define the average function Define the main function which will include the following things 1. prompt user for input of text file name 2. open and read input file, can be done before or inside high order functions 3. use two high order functions 4.calculate and display averages and original ist...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the user for two words b. Print out how many words in the file fall between those words c. If one of the two words is not contained in the file, print out which word is not found in the file d. If both words are not found in the file, print out a message e. Sample output: Please type in two words: hello computer...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional int array. Your program must (1) read the name of the file from the command-line arguments, (2) open the file, (3) check that each line has the same number of characters and (4) check that the only characters in a line are ones and zeros. If there is no such command-line argument or no such file, or if any of the checks fail, your...
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression...
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression from the user, and then prints every line that matches the RE.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT