将文本文件读入Stack并按相反顺序打印出元素



我正在尝试读取一个文本文件(文本行(,使用push方法将所有元素放入堆栈中。一旦我这样做,我计划使用pop方法逐行打印所有元素。

  • 一次读取一行输入,然后将行写入
  • 按相反的顺序,以便先打印最后一行输入,然后
  • 倒数第二个输入行等等
class part1{
//pushing element on the top of the stack 
static void stack_push(Stack<String> stack){
for(int i = 0; i< stack.length(); i++){
stack.push(i);
}
}
static void stack_pop(Stack<String> stack){
System.out.println("Pop :");
for(int i = 0; i < stack.length(); i++){
String y = (String) stack.pop();
System.out.println(y);
}
}
public static void main(String args[]){
BufferedReader br = new BufferedReader(new FileReader("randomFile.txt"));
stack_push(br);
}
}

读取文件并将其内容推入堆栈的迭代("经典"(方法:

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();
}
}

最新更新