Write a program that reads an input file then print the input file data to an ou
ID: 3828589 • Letter: W
Question
Write a program that reads an input file then print the input file data to an output file but with the following additions
1. each line in the outpfile is prefixed with the current line number, first line with 1. Second line with 2. etc
2. all empty lines or lines containing all blanks are not to be written to the output file
3. The program must not throw a FileNotFoundException, rather it should catch the exception in the program and ask the user again for a new input file name. Keep repeating until no exception is generated from opening the file to read and write.
Sample run if file Lab.java does not exist and Lab4.java exists
Please enter input file name: Lab.java
Please enter outputfile name: Lab.out
File does not exist
Please enter input file name: Lab4.java
Please enter outputfile name: Lab.out
Input File :
public class Lab4
{
public static void main(String[] args) throws FileNotFoundException
{
String a = "c3.txt";
String x = "xyz.txt";
File b = new File(a);
Scanner in = new Scanner(b);
Scanner key = new Scanner(System.in);
String data = "";
while (in.hasNextLine())
{
data += in.nextLine();
}
String d = key.next();
d = key.next();
d = d + data;
System.out.println(d);
}
}
Output file
1.public class Lab
2.{
3. public static void main(String[] args) throws FileNotFoundException
4. {
5. String a = "c3.txt";
6. String x = "xyz.txt";
7. File b = new File(a);
8. Scanner in = new Scanner(b);
9. Scanner key = new Scanner(System.in);
10. String data = "";
11. while (in.hasNextLine())
12. {
13. data += in.nextLine();
14. }
15. String d = key.next();
16. d = key.next();
17. d = d + data;
18. System.out.println(d);
19.
20. }
21.}
Explanation / Answer
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteNumberedFile {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.print("Please enter input file name: ");
String inputFile = sc.nextLine();
System.out.print("Please enter outputfile name: ");
String outputFileName = sc.nextLine();
System.out.println();
try {
FileReader fr = new FileReader(inputFile);
Scanner fileScanner = new Scanner(fr);
FileWriter fw = new FileWriter(outputFileName);
int count = 0;
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
if (line.trim().length() > 0)
{
fw.write(count + "." + line + " ");
count++;
}
}
fw.close();
fileScanner.close();
fr.close();
break;
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
catch(IOException e)
{
System.out.println("Unable to write to file.");
}
}
sc.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.