Чтение текстового файла в стек и распечатка элементов в обратном порядке - PullRequest
0 голосов
/ 04 мая 2020

Я пытаюсь прочитать текстовый файл (строки текста), помещая все элементы в стек, используя метод pu sh. Как только я это сделаю, я планирую печатать все элементы построчно, используя метод 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);
    }

}

1 Ответ

0 голосов
/ 04 мая 2020

Итеративный ("классический") подход чтения файла и помещения его содержимого в стек:

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