Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

***JAVA*** You will design a program that reads and writes to a file. The specif

ID: 3686658 • Letter: #

Question

***JAVA***

You will design a program that reads and writes to a file.

The specifications are:

There will be a text file that your program will read.

There will be a second text file that your program will write to.

The textfile can be a file you created, or a text file you found on the internet. Your choice. There must be two separate textfiles.

As a hint, here is a textfile you can use - file named names.txt with line(1) Smith, Bob (2) Johnson, Brady (3) Brody, Jessica (4) Hanson, Martin

Another hint....the textfile should be in the same directory as the program.

Explanation / Answer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ReadWriteFileDemo {
  
   public static void main(String[] args) throws IOException {
      
       Scanner sc = new Scanner(System.in);
      
       //reading file names
       System.out.print("Enter input file name: ");
       String input = sc.next();
       System.out.print("Enter ouput file name: ");
       String output = sc.next();
       // opening input file
       FileReader fr = new FileReader(input);
       BufferedReader br = new BufferedReader(fr);
      
       // opening output file
       FileWriter fw = new FileWriter(output);
       BufferedWriter bw = new BufferedWriter(fw);
      
       String line;
      
       // reading line by line and stroing into output file
       while((line = br.readLine()) != null){
           bw.write(line);
           bw.newLine();
       }
      
       //closing files
       bw.close();br.close();fr.close();fw.close();
   }

}