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

I need my code to read from a text file and write out a seperate text file. The

ID: 675148 • Letter: I

Question

I need my code to read from a text file and write out a seperate text file. The new text file should contain all the same lines of text as the input file with the addition of a line number appended as the first character on the line.

Ex: if the input line reads:

this is a test

the output should read

1. this is a test

This is my code so far:

package m6;

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

/**
*
* @author AHiggins
*/
public class M6 {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// TODO code application logic here
try
{
FileInputStream fis = new FileInputStream("\GHCDDSVR1\RedirectedFolders\AHiggins\MyDocuments\AshleySchool\Chapter11.txt");
FileOutputStream fos = new FileOutputStream("\GHCDDSVR1\RedirectedFolders\AHiggins\MyDocuments\AshleySchool\ahiggins.txt");
  
Scanner scan = new Scanner(fis);
PrintWriter pw = new PrintWriter(fos);
  
int lineNumber = 1;
  
while(scan.hasNextLine())
{
String stringRead = scan.nextLine();
pw.println(lineNumber + ": " + stringRead);
lineNumber++;
}
  
pw.close();
}
  
catch(FileNotFoundException fnf)
{
System.out.println("");
  
}
}
  
}

Explanation / Answer

package m6;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Scanner;

/**

*

* @author AHiggins

*/

public class M6 {

/**

   * @param args the command line arguments

   * @throws IOException

   */

public static void main(String[] args) throws IOException {

// TODO code application logic here

try

{

File fis = new File("\GHCDDSVR1\RedirectedFolders\AHiggins\MyDocuments\AshleySchool\Chapter11.txt");

FileOutputStream fos = new FileOutputStream("\GHCDDSVR1\RedirectedFolders\AHiggins\MyDocuments\AshleySchool\ahiggins.txt");

  

PrintWriter pw = new PrintWriter(fos);

  

int lineNumber = 1;

  

BufferedReader br = new BufferedReader(new FileReader(fis));

String line;

while ((line = br.readLine()) != null) {

   pw.println(lineNumber + ": " + line);

lineNumber++;

}

  

  

pw.close();

br.close();

}

  

catch(FileNotFoundException fnf)

{

System.out.println("");

  

}

}

  

}