首页 > 解决方案 > 使用 Java 将文本文件中的内容读入 ArrayList

问题描述

我在将内容从文件移动到 ArrayList 时遇到问题。用户通过他想要添加到 ArrayList 的索引从文件中选择一行。我试过 quick.add(new Pastatas()); 但正如我所见,它将在那里添加我的空构造函数。

private void myobj() {
    File FILE = new File(filex);
    if (FILE.exists() && FILE.length() > 0) {
        try {
            Scanner SC = new Scanner(FILE);
            for (int i = 0; i < FILE.length(); i++) {
                if (SC.hasNextLine()) {
                    String storage = SC.nextLine();
                    System.out.println("ID: " + i + " " + storage);
                }
            }
            System.out.println("select one.");
            Scanner sc = new Scanner(System.in);
            int userInputas = Integer.parseInt(sc.nextLine());
            for (int j = 0; j < FILE.length(); j++) {
                if (userInputas == j) {
                    quick.add(/*Probably problem here*/)
                }
            }
        } catch (IOException e) {
            System.err.println(e.getMessage() + "error");
        }
    }

标签: javajava-8java-io

解决方案


Path, Paths, Files对此类任务使用较新的。

    Path path = Paths.get(filex);
    List<String> lines = Files.readAllLines(path);

    System.out.println("Select one.");
    Scanner sc = new Scanner(System.in);
    int lineno = Integer.parseInt(sc.nextLine()); // Maybe 1 based
    int index = lineno - 1; // Zero based index

    if (0 <= index && index < lines.size()) {
        String line = lines.get(index);
        System.out.println("Selected: " + line);
        quick.add(line);
    }

逻辑错误:

FILE(或Path以上)只是文件的可能不存在的名字对象/名称。长度是字节数,文件大小。因此,对于选择文本行,必须执行不同的操作,例如打开、读取并最终关闭文件。该类Files提供实用功能来执行诸如加载所有行之类的操作。


阅读您的评论后;也许更像:

quick.add(new Pastatas(line));

事实上,如果文件不是文本文件,我们需要知道文件是如何填充的。


推荐阅读