我在java中遇到问题,我不明白为什么,因为我觉得我在做文本书。
想要做的概述是:
代码
添加文件:
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迭代。
以下是我从debbuging印刷品中得到的结果:
the line readed from file--
is the line null: false
line length: 0
Tokenizer starts with string:
任何人都可以帮我吗?
答案 0 :(得分:3)
只有当您用尽了流时,才会获得null
。但是流的第一行(你的文件)只是一个空行 - 你加载它,空行的结果是一个空字符串(""
)。通过在string.length() == 0
循环中添加以下内容,使用while
跳过行可轻松解决此问题:
if (line.length() == 0) continue;
您可能还需要在检查长度之前考虑使用trim()
,以避免出现令人讨厌的空格string.length() > 0