Write a program that opens a Java source file adds line numb

Write a program that opens a Java source file, adds line numbers, and saves the result in a new file. Line numbers are numbers which indicate the different lines of a source file, they are useful when trying to draw someone\'s attention to a particular line (e.g., \"there\'s a bug on line 4\"). Your program should prompt the user to enter a filename, open it, and then save each line to an output fix with the line numbers prepended to the beginning of each line. Afterward, display the name of the output file. The name of the output file should based on the input file with the \'.\' replaced by a \'_\' and \".txt\" added to the end. Please enter the name of a java source file; Saving source code with line number to Testintegers_java.txt public class TestingArea {public static void main(String[] args) {String[] data = {\"100\", \"200\", \"222\", \"232\", null, \"250\"}; try {try {for(int i = 0; i

Solution

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;


public class PrintLineNum {

    public static void main(String[] args) throws IOException {
        Scanner inputScanner = new Scanner(System.in);

        // Prompting the user for a Java Source File
        System.out.println(\"Please enter the name of a Java Source File:\");
        String javaSourceFileName = inputScanner.nextLine();

        // Read the file.
        String currentLineofCode;

        // Output file name formatting
        String javaSourceFileNameWithLineNumber = javaSourceFileName.replace(\".\", \"_\");
        javaSourceFileNameWithLineNumber += \".txt\";

        PrintWriter writer = new PrintWriter(javaSourceFileNameWithLineNumber, \"UTF-8\");

        
        // The following is a auto-closable try block to read the source file, append line num and populate in the output file.
        try(BufferedReader bReader = new BufferedReader(new FileReader(javaSourceFileName))){
            int lineNum = 0;
            while ((currentLineofCode = bReader.readLine()) != null) {
                System.out.println(currentLineofCode);
                writer.printf(\"%03d:\", ++lineNum);
                writer.print(currentLineofCode);
                writer.println();
            }
        }

        inputScanner.close();
        writer.close();

    }
}

 Write a program that opens a Java source file, adds line numbers, and saves the result in a new file. Line numbers are numbers which indicate the different lin

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site