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

Create a Java NetBeams project named AdLineNumbers Create a Java NetBeans projec

ID: 3851467 • Letter: C

Question

Create a Java NetBeams project named AdLineNumbers Create a Java NetBeans project named AddLineNumbers with the main class named AddLineNumbers . This program will read data from a text file "datalnput.txt" and while there are more records, prepend a line number to the text data and output the concatenated data to "dataOutput.txt" implementing a try/catch block to catch any file errors thrown by the JVM. After you have created your NetBeans project AddLineNumbers and before you attempt to execute your application download and/or copy the text data file dataInput.txt from the course Blackboard link below to your AddLine Numbers pr oject folder.

Explanation / Answer


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;


/**
*
* @author Sam
*/
public class AddLineNumbers {

    public static void main(String[] args) {
        String line;
        Scanner sc;
        PrintWriter pw;
        int lineNumber = 0;
        try {
            sc = new Scanner("dataInput.txt");
            FileOutputStream fos = new FileOutputStream("dataOutput.txt");
            pw = new PrintWriter(fos);
            while (sc.hasNextLine()) {
                line = sc.nextLine();
                lineNumber++;
                pw.println(lineNumber + " " + line);
            }

            sc.close();
            pw.close();

        } catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
            System.err.println(ex.toString());
            ex.printStackTrace();
        }
    }
}

INPUT:

/** data input
* Anderson, Franceschi
*/
public class Hello
{
   public static void main( String [] args )
   {
       System.out.println( "Hello" );
   }
}

OUTPUT:

1 /** data input
2 * Anderson, Franceschi
3 */
4 public class Hello
5 {
6    public static void main( String [] args )
7    {
8        System.out.println( "Hello" );
9    }
10 }