Question: Java: Modify your program in Lab Assignment 1 to throw an exception if the file does not exist. An error message should result. Use the
Java: Modify your program in Lab Assignment 1 to throw an exception if the file does not exist. An error message should result. Use the same file name in your program as 1, however, use the new input file in 2 assignment dropbox.
Lab 1: Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. Test with the input file attached.
For example if file input is:
This is a test
File output should be
1. This is a test
Input file:
This file contains
lines of text to
determine if you can
properly read and
write from a file
using exceptions.
code:
mport java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class FileReadWriteWithLineNumber{
public static void main(String[] args) throws Exception{
double salary, percernt;
BufferedWriter bw = null;
FileWriter fw = null;
Scanner scanner = new Scanner(System.in);
System.out.println("This is a test: ");
String inputFileName = scanner.nextLine();
System.out.println("1. This is a test: ");
String outputFileName = scanner.nextLine();
Scanner sc = new Scanner(new File("C:\\INPUTFILE.txt"));
fw = new FileWriter("C:\\OUTPUTFILE.txt");
bw = new BufferedWriter(fw);
String line;
int i = 1;
while(sc.hasNext()){
line = sc.nextLine();
bw.write(i+". "+line+" ");
i++;
}
bw.close();
sc.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
