Java:当并非所有行都有新行时从文件中读取行

标签 java string file java.util.scanner

我正在开发一个程序,该程序打开一个数据文件并使用 while 循环逐行读取该文件,以将数据存储在二叉搜索树中。我唯一的问题是我不确定如何处理循环条件,因为文件的最后一行没有换行符。我通常使用 hasNextLine() 和扫描仪来读取文件,但这会在我的程序中引发错误,并且我不能使用 hasNext() 因为我需要抓取整行,而不仅仅是其中的一部分。解决这个问题的最佳方法是什么?

    public static BinaryTree getInventory(BinaryTree tree, Scanner input) {
    String line, title = "";
    int available = -1, rented = -1, comma = 0;
    boolean quote = true;

    // While not the end of file
    while (input.hasNextLine()) {
        line = input.nextLine();

        for (int i = 1; i < line.length(); i++) {
            if (line.charAt(i) == '"') {
                title = line.substring(1, i);
                comma = i + 1;
                quote = false;
                i++;
            } 
            else if (line.charAt(i) == ',' && !quote) {
                available = Integer.parseInt(line.substring(comma + 1, i - 1));
                comma = i;
                i++;
            } 
            else if (i + 1 == line.length()) {
                rented = Integer.parseInt(line.substring(comma + 1, i));
            }

        }
        tree.insert(new Node(title,available,rented));
    }
    return tree;
}

最佳答案

您可以通过捕获 NoSuchElementException 来避免使用 hasNext()。另外,考虑到文件的结构(似乎是 "title",XX,YY),您可以避免使用这样的代码循环遍历行字符

try {
    while (true) {
        String line = input.nextLine();
        int rdquo = line.indexOf('"', 1);
        String title = line.substring(1, rdquo);
        String[] avail = line.substring(rdquo+2).split(",");
        tree.insert(new Node(title, Integer.parseInt(avail[0]) , Integer.parseInt(avail[1]));
    }
} catch (NoSuchElementException reachedEndOfFile) { }

关于Java:当并非所有行都有新行时从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328604/

相关文章:

java - infinispan 服务器上的 JDBC_PING 不工作

string - grep 两个文件 (a.txt, b.txt) - b.txt 中有多少行以 a.txt 中的单词开头(或结束) - 输出 : 2 files with the results

java - 发送更改的 hashmap 但使用 ObjectOutputStream 和 ObjectInputStream 获得相同的 hashmap

java - 在 param 中传递类常量

arrays - 如何使用 REGEX 按相同的符号序列拆分字符串?

python - 从一个文件读取数据丢失,处理并写入另一个文件? Python

java - 搜索整个C盘的文件类型

c++ - 读取文件到内存,遍历数据,然后写入文件

java - 如何更正后查询的更改编码?

java - 哪种是杀死线程的最简洁和/或最有效的方法