如何通过扫描仪读取文本文件

How To Read A Text File Via Scanner

我正在尝试从文本文件中读取,但每当程序进入我的 while 循环时,它就会跳过它。我用了一个之前的例子,我不得不检查一下我是否做对了,但这次它似乎没有用。

编辑:澄清一下,下面带有 "b++" 的部分被跳过了。

编辑 2:更新代码。

    public static void main(String[] args) throws FileNotFoundException {

    ToDoItem td = new ToDoItem();
    ToDoList tl = new ToDoList();

    File file = new File("ToDoItems.txt");
    Scanner ReadFile = new Scanner(file);
    Scanner keyboard = new Scanner(System.in);

    ArrayList<String> list = new ArrayList<>();
    String inputline;

    System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");

    try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {

        do {
            System.out.println("add to the list? [y/n]");
            inputline = keyboard.nextLine();

            if ("y".equals(inputline)) {
                fout.print(td.getDescription() + "\n");

            } else {
                System.out.println("Here is the list so far:");

                while (ReadFile.hasNext()) {
                    String listString = ReadFile.nextLine();
                    list.add(listString);

                }
            }
        } while ("y".equals(inputline));

    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
    }
    System.out.println(list);
}

理想情况下,我希望它在每次通过 while 循环时打印数组的一部分。但它最终只是跳过了它。 我检查了文本文件本身,它确实有我想要打印的信息。但由于某种原因,扫描仪无法正确读取它。

String[] stringArray = new String[b]; 有问题,因为您的 int b = 0;.

此外,您似乎甚至不知道您的阵列有多大。我建议您改用 ArrayList 。这样你就不需要计数器,只需添加到 ArrayList。

最好 trycatch 你的 FileNotFoundException 而不是扔 main 但我想你知道你的文件将永远在那里。

我猜你的问题是你正在尝试读取你当前正在使用的文件,在读取它之前尝试关闭 fout 对象,像这样:

public static void main(String[] args){
    File file = new File("ToDoItems.txt");
    ToDoItem td = new ToDoItem();
    ToDoList tl = new ToDoList();

    Scanner keyboard = new Scanner(System.in);

    ArrayList<String> list = new ArrayList<>();
    String inputline;

    System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
    try (PrintWriter fout = new PrintWriter(file)) {
    //                                       ^^ here
        do {
            System.out.println("add to the list? [y/n]");
            inputline = keyboard.nextLine();

            if ("y".equals(inputline)) {
                fout.print(td.getDescription() + System.lineSeparator());
            } else {
                // Important line is here!
                fout.close(); // <--- Close printwriter before read file

                System.out.println("Here is the list so far:");
                Scanner ReadFile = new Scanner(file);

                while (ReadFile.hasNext()) {
                    String listString = ReadFile.nextLine();
                    list.add(listString);
                }
            }
        } while ("y".equals(inputline));
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
    }
    System.out.println(list);
}