Write a java program that would ask the user to enter an inp

Write a java program that would ask the user to enter an input file name, and an output file name. Then the program reads the content of the input file, and then writes the content of the input file to the output file with each line proceeded with a line number followed by a colon. The line numbering should start at 1.

should be used the following technique
(a) while loop should be used to complete the program.

(b)Scanner classisused
(c) PrintWriter class is used
(d) The files are closed before the program terminates.

Example

Original Input file Output file with line number added
134 1: 134
125 2: 125
112 3: 112
189 4: 189

Solution

FileCopier.java:-

import java.io.File;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileCopier {

   public static void main(String[] args) throws IOException{
       Scanner in=new Scanner(System.in);
       System.out.println(\"Enter input file\");
       File inputFile=new File(in.nextLine());
       if(!inputFile.exists()){
           System.out.println(\"Source file doesn\'t exist\");
           System.exit(0);
       }
       FileInputStream fis=new FileInputStream(inputFile);
       System.out.println(\"Enter output file\");
       FileWriter fw=new FileWriter(in.nextLine());
       PrintWriter pw=new PrintWriter(fw);
      
       in=new Scanner(inputFile);
       int i=1;
       while(in.hasNextLine()){
           String s=in.nextLine();
           pw.write(i++ + \": \" + s + \"\ \");
       }
      
       pw.flush();pw.close();
   }

}


Console output:

Enter input file
test.txt
Enter output file
output.txt


Sample run 1:-

test.txt:
hey
123
.
howdy

output.txt:
1: hey
2: 123
3: .
4: howdy

Sample run 2:-

test.txt:
123
345
567
789

output.txt
1: 123
2: 345
3: 567
4: 789

Write a java program that would ask the user to enter an input file name, and an output file name. Then the program reads the content of the input file, and the
Write a java program that would ask the user to enter an input file name, and an output file name. Then the program reads the content of the input file, and the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site