Write a public static method called writeTokensToLines that will read an input f
ID: 3551525 • Letter: W
Question
Write a public static method called writeTokensToLines that will read an input file one token at a time
using Scanner, and write the tokens to a file using a PrintWriter, one token per line, with the tokens
numbered starting at 1. For example, if the input file has just one line with the content "in the morning",
writeTokensToLines should create a file with the content shown below. (Hints: Make sure to use trycatch
blocks as needed. Also, make sure to instantiate Scanner properly.)
1. in
2. the
3. morning
public static void writeTokensToLines(String inFileName, String outFileName)
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileReaderWriter {
public static void main(String[] args) {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
String textToWrite;
int i=0;
try{
Scanner reader = new Scanner(inputFile);
PrintWriter writer = new PrintWriter(outputFile);
while(reader.hasNext()){
i++;
textToWrite = i+". "+reader.next();
writer.println(textToWrite);
writer.flush();
}
//closing the streams
reader.close();
writer.close();
}
catch(FileNotFoundException e){
System.err.println("Input file not found.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.