Write the program in Java: Your assignment is to write a program that reads the
ID: 3684828 • Letter: W
Question
Write the program in Java:
Your assignment is to write a program that reads the attached text file and writes out a separate text file (using your first initial and last name as the filename). 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 your input line reads:
this is a test
your output should read
1. this is a test
Chapter-11.txt File:
The first step to a career in technology is curiosity.
The next step is passion and drive.
The third step is accountability and humility - willingness to admit
that you can never possibly know everything; especially since it changes every second.
A final step is knowing how to communicate. Maybe you are the smartest person in the room,
but who cares if you cannot communicate your knowledge to others?
"Do or do not. There is no try" - yoda
Explanation / Answer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class AppendLineNumber {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter input filename: ");
String inputFile = sc.next();
System.out.print("Enter output filename: ");
String outputFile = sc.next();
// declaring reader and writer
FileReader freader = new FileReader(inputFile);
BufferedReader breader = new BufferedReader(freader);
FileWriter fwriter = new FileWriter(outputFile);
BufferedWriter bwriter = new BufferedWriter(fwriter);
String line;
int linenumber = 1;
//reading line by line and appending line number before writing
while((line = breader.readLine())!=null){
// appending line number
line = linenumber + "." + line;
bwriter.write(line);
bwriter.newLine();
linenumber++;
}
freader.close();
bwriter.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.