Write a program, Lab2InputOutput.java, that reads a file containing text. The na
ID: 3786976 • Letter: W
Question
Write a program, Lab2InputOutput.java, that reads a file containing text. The name of the input file will be provided by a user of your program as a (the first) command line argument to your program (see lecture 2_1 or the textbook for a reminder on command line arguments) Prompt the user (system. in) for the name they want to use for the output file using the console. For this part you do not need to handle the exception. Rather, you can just "throws" it to the main level and have the stack trace printed. Read each line and send it to the output file, preceded by line numbers Example If the input file is Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go! then the program produces the output file/astir 1 astir/Mary had a little lamb/astir 2 astir/Whose fleece was white as snow/astir 3 astir/And everywhere that Mary went, /astir 1 astir/The lamb was sure to go!Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Lab2InputOutput {
// function to take input and output file name, and write content of input
// file to output file
public static void writeToOutputFile(String inputFile, String outputFile) throws IOException{
// Opening input and output file reader and writer
FileReader reader = new FileReader(new File(inputFile));
BufferedReader br = new BufferedReader(reader);
FileWriter fw = new FileWriter(new File(outputFile));
BufferedWriter bw = new BufferedWriter(fw);
int lineNumber = 0;
String line = "";
while((line = br.readLine()) != null){
lineNumber++;
bw.write(lineNumber+" "+line);
bw.newLine();
}
// closing files object
br.close();
bw.close();
}
public static void main(String[] args) throws IOException {
// command line input check
if(args == null || args.length == 0){
System.out.println("Please pass input file name from command line");
System.exit(0);
}
Scanner sc = new Scanner(System.in);
System.out.print("Enter output file name: ");
String outputFile = sc.next();
writeToOutputFile(args[0], outputFile);;
}
}
########### input.txt ##############
line1
line2
line3
line4
line5
line6
########### output.txt ##############
1 line1
2 line2
3 line3
4 line4
5 line5
6 line6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.