Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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.");

}


}


}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote