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

java Write a function that opens a text file and reads its contents into a stack

ID: 3724256 • Letter: J

Question

java

Write a function that opens a text file and reads its contents into a stack of characters. The program should then pop the characters from the stack and save them in a second text file. The order of the characters saved in the second file should be the reverse of their order in the first file.

Explanation / Answer

import java.io.*; import java.util.ArrayDeque; import java.util.Queue; import java.util.Stack; public class FileReverse { public static void reverseFile(String inputFileName, String outputFileName) { try { FileInputStream in = new FileInputStream(new File(inputFileName)); FileOutputStream out = new FileOutputStream(outputFileName); Stack stack = new Stack(); while(in.available() > 0) { stack.push((char) in.read()); } while (!stack.isEmpty()) { out.write(stack.pop()); } out.flush(); out.close(); in.close(); } catch (FileNotFoundException e) { System.out.println("Can not open " + inputFileName + " to read"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { reverseFile("input.txt", "output.txt"); } }