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

(JAVA) Write a public static method called tokensToLinesR that will read an inpu

ID: 3680272 • Letter: #

Question

(JAVA) Write a public static method called tokensToLinesR that will read an input file one token at a time using
Scanner , and print them to an output file using PrintWriter , in reverse order For example, if the input
file has just one line with the content "in the morning", tokensToLinesR should create a file with the
content shown below. (Hints: Make sure to use try-catch blocks as needed and close the PrintWriter.
Also, make sure to instantiate Scanner properly. Use scan.next() to get a token from the file. You have to
store the tokens before printing them out since your print them in the opposite order that you read them.)

morning
the
in

public static void tokensToLinesR(String inFileName, String outFileName)

Explanation / Answer

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;

public class HelloWorld{

    public static void main(String[] args)
    {
        HelloWorld.tokensToLinesR();
    }
private static void tokensToLinesR() {

        try {

            FileReader inputFileReader   = new FileReader("InputFile.txt");
            FileWriter outputFileReader = new FileWriter("OutputFile.txt");

            // Create Buffered/PrintWriter Objects
            BufferedReader inputStream   = new BufferedReader(inputFileReader);
            PrintWriter    outputStream = new PrintWriter(outputFileReader);
            String token[]=new String[100];
            int i=0;
            outputStream.println();

            String inLine = null;

            while ((inLine = inputStream.readLine()) != null) {
                token[i++]=inLine;
            }

            outputStream.println();

            outputStream.close();
            inputStream.close();
          
            System.out.println("Printing the contents of file in reverse order");
            for(int j=i-1;j>=0;j--)
            outputStream.println(token[j]);

        } catch (IOException e) {

            System.out.println("IOException:");
            e.printStackTrace();

        }

    }

}