java - 读取文件时行为空但行不为空

标签 java bufferedreader java-io

我有一个 java 问题,我不明白为什么,因为我认为我正在做教科书的东西。

想要做的事情的概述是:

  1. 我想创建一个文件,每行包含两个字符串:documentPath、documentID(格式为:“documentPath;documentID;”)
  2. 我希望能够在文件末尾添加行并将文件加载到 Java 数据结构,比如说 HashSet。
  3. 每次我想添加一个新行时,我都会将所有文件加载到 HashSet 中,检查我要添加的行是否不存在,并最终将其添加到末尾。 (数据量小-不关心效率)

代码

添加文件:

public void addFile(String documentPath) {
    this.loadCollection(); //METHOD IS NOT CONTINUING: ERROR HERE
    if (!documentsInfo.contains(documentPath)) {
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(this.collectionFile, true)));
            DocumentInfo documentInfo = new DocumentInfo(documentPath, ++this.IDcounter);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

加载文件:

    public void loadCollection() {
    if (loaded) {return;} 

    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader(collectionFile));

        String line;
        while ( (line = br.readLine())!= null ) { //PROBLEM HERE
            System.out.println("the line readed from file-" + line + "-");
            System.out.println("is the line null: "+ (line==null));
            System.out.println("line length: " + line.length());
            DocumentInfo documentInfo = new DocumentInfo(line);
            documentsInfo.add(documentInfo);
        }
        br.close();
        open = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

创建要添加的行:

public DocumentInfo(String fileLine) {
    String delimiter = Repository.DOCUMENT_FILE_SEPARATOR;
    StringTokenizer tok = new StringTokenizer(fileLine, delimiter);

    System.out.println("Tokenizer starts with string: " + fileLine);

    this.documentPath = tok.nextToken(); //EXCEPTION here
    this.documentId = Integer.parseInt(tok.nextToken());
}

public String toString() {
    String sep = Repository.DOCUMENT_FILE_SEPARATOR;
    return this.getDocumentPath()+sep+this.getDocumentId()+sep+"\n";
}

当我尝试获取 nextToken 时,我在 Tokenizer 方法 (java.util.NoSuchElementException) 中遇到异常,但问题来自 loadCollection() 方法。我第一次读取文件的内容时什么也没有,该行是空的(长度:0)但该行不为空,因此 while 条件无法停止 while 迭代。

这是我从调试打印中得到的:

the line readed from file--
is the line null: false
line length: 0
Tokenizer starts with string:

谁能帮我解决这个问题?

最佳答案

只有当流耗尽时,您才会得到一个null。但是流的第一行(你的文件)只是一个空行 - 你加载它,空行的结果是一个空字符串(“”)。通过在 while 循环中添加以下内容,可以通过使用 string.length() == 0 跳过行来轻松解决此问题:

if (line.length() == 0) continue;

您可能要考虑使用 trim()在检查长度之前,避免令人讨厌的空格使 string.length() > 0

关于java - 读取文件时行为空但行不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28168503/

相关文章:

java - 将自定义 logging.properties 与 Jersey 一起使用

java - 将数据保存在 vector 中并在其他函数中重用

java - Perl 兼容正则表达式引擎 : how implemented?

java - 插入命令上的 SQLite 外键不匹配

java - 无法抗拒工作

Java Hashmap,其中键是文件,值是模型

java - BufferedReader 和 BufferedWriter

java - BufferedReader 不读取整个文本文件

java - AWS Lambda - 缓冲读取器

Java,读取txt文件最快的类