Итеративный ("классический") подход чтения файла и помещения его содержимого в стек:
public static void main(String args[]) {
String fileName = "randomFile.txt";
// create a bufferedReader
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
// create a stack (Note: do not use the Stack class here, it is inherited from Vector which is deprecated.)
Deque<String> stack = new ArrayDeque<>();
// read the file line by line and push the lines into the stack
String line;
while ((line = bufferedReader.readLine()) != null) {
stack.push(line);
}
// pop the values from the stack and print them
while (stack.peek() != null) {
System.out.println(stack.pop());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Декларативный ("современный") подход:
public static void main(String args[]) {
String fileName = "randomFile.txt";
// create stream from the input file
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
// create a stack (Note: do not use the Stack class here, it is inherited from Vector which is deprecated.)
Deque<String> stack = new ArrayDeque<>();
// push the lines from the stream into the stack
stream.forEach(stack::push);
// print the lines from the stack (Note: the stack is not modified here!)
stack.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}