Write a class “LineNumbers” that has the method “parseData” (below) which reads
ID: 3721477 • Letter: W
Question
Write a class “LineNumbers” that has the method “parseData” (below) which reads a file containing text. The program counts the number of characters in that file and the number of characters per each line. It then writes that information, along with the contents of the read file, to an output file.
public static void parseData(File inputFile, File outputFile){ //Your code here }
Use Scanner to read the contents of the input file and use PrintWriter to write out to the output file. Use string formatting to get the correct output. Each line after the first should be a print-formatted string where: the number of characters in the line is a left justified String, width 10, and the content of the line itself is a right justified string of length 1. Be sure to include appropriate comments throughout your code and choose meaningful variable names.
So if the input file is:
`Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
Your program should write EXACTLY this to “output.txt”:
The file contains 124 characters
35 `Twas brillig, and the slithy toves
32 Did gyre and gimble in the wabe:
29 All mimsy were the borogoves,
28 And the mome raths outgrabe.
Explanation / Answer
input.txt
`Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
_______________
LineNumbers.java
package org.students;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class LineNumbers {
public static void main(String[] args) {
//Creating file objects
File inputFile=new File("input.txt");
File outputFile=new File("output.txt");
//calling the function
parseData(inputFile, outputFile);
}
public static void parseData(File inputFile, File outputFile)
{
String str="";
FileWriter fw=null;
int totChars=0;
try {
//Opening the input file
Scanner sc=new Scanner(inputFile);
//Opening the output file
fw=new FileWriter(new File("output.txt"));
while(sc.hasNext())
{
str=sc.nextLine();
totChars+=str.length();
}
sc.close();
fw.write("The file contains "+totChars+" characters ");
//Opening the input file
sc=new Scanner(inputFile);
while(sc.hasNext())
{
str=sc.nextLine();
fw.write(str.length()+" "+str+" ");
}
sc.close();
fw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
_________________
Output:
output.txt
The file contains 124 characters
35 `Twas brillig, and the slithy toves
32 Did gyre and gimble in the wabe:
29 All mimsy were the borogoves,
28 And the mome raths outgrabe.
____________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.