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

Line when reading a file is empty but the line is not null

我在 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