【发布时间】:2015-03-25 22:49:33
【问题描述】:
我在 java 中有一个问题,我不明白为什么,因为我认为我在做教科书的东西。
想要做什么的概述是:
- 我想创建一个文件,每行包含两个字符串:documentPath、documentID(格式为:“documentPath;documentID;”)
- 我希望能够在文件末尾添加行并将文件加载到 Java 数据结构中,比如 HashSet。
- 每次我想添加一个新行时,我都会将所有文件加载到一个 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。但是流的第一行(您的文件)只是一个空行 - 您加载它,空行的结果是一个空字符串("")。用string.length() == 0跳行即可轻松解决
标签: java bufferedreader java-io