在Java中从目录读取文件时出现奇怪的错误
编辑:子目录是一个目录数组。这段代码在此数组中循环,以便进入每个目录并将列出的所有文件加载到数组Web中。然后,对于每个文件,readFile函数应该读取该文件 我的代码是:在Java中从目录读取文件时出现奇怪的错误,java,filesystems,Java,Filesystems,编辑:子目录是一个目录数组。这段代码在此数组中循环,以便进入每个目录并将列出的所有文件加载到数组Web中。然后,对于每个文件,readFile函数应该读取该文件 我的代码是: for (File cat: children) { File[] webs = cat.listFiles(); System.out.println(" Indexing category: " + cat.getName()); for (File f: webs) {
for (File cat: children) {
File[] webs = cat.listFiles();
System.out.println(" Indexing category: " + cat.getName());
for (File f: webs) {
Web w = readFile(f);
// Do things with w
}
}
我得到了这个错误:
org.htmlparser.util.ParserException: Error in opening a connection to 209800.webtrec
209801.webtrec
...
422064.webtrec
422071.webtrec
422087.webtrec
422089.webtrec
422112.webtrec
422125.webtrec
422127.webtrec
;
java.io.IOException: File Name Too Long
at java.io.UnixFileSystem.canonicalize0(Native Method)
at java.io.UnixFileSystem.canonicalize(UnixFileSystem.java:172)
at java.io.File.getCanonicalPath(File.java:576)
at org.htmlparser.http.ConnectionManager.openConnection(ConnectionManager.java:848)
at org.htmlparser.Parser.setResource(Parser.java:398)
at org.htmlparser.Parser.<init>(Parser.java:317)
at org.htmlparser.Parser.<init>(Parser.java:331)
at IndexGenerator.IndexGenerator.readFile(IndexGenerator.java:156)
at IndexGenerator.IndexGenerator.main(IndexGenerator.java:101)
好了,我终于找到了解决办法
这是一个非常愚蠢的错误。我在那个目录中有一个文件,其中包含我在上一个任务中删除的所有空html文件的名称。所以,我试图解析它,然后解析器将它解释为URL,而不是htmlfile(因为没有标记和很多点…)。我无法轻松找到该文件,因为该文件夹中有数百万个文件。什么是
子文件夹
?它来自哪里?什么是readFile
?向我们展示它的源代码。它应该做什么?您能打印引发异常的文件名吗?您的Java版本是什么?如果你没有太长的命名文件,你可以尝试更新你的Java,这也可能是一个bug。。。我会尽力的,谢谢@Kits89您应该显示readFile
的内容,因为这是发生异常的原因。
private static Web readFile(File file) {
try {
FileInputStream fin = new FileInputStream(file);
FileChannel fch = fin.getChannel();
// map the contents of the file into ByteBuffer
ByteBuffer byteBuff = fch.map(FileChannel.MapMode.READ_ONLY,
0, fch.size());
// convert ByteBuffer to CharBuffer
// CharBuffer chBuff = Charset.defaultCharset().decode(byteBuff);
CharBuffer chBuff = Charset.forName("UTF-8").decode(byteBuff);
String f = chBuff.toString();
// Close imputstream. By doing this you close the channel associated to it
fin.close();
Parser parser = new Parser(f);
Visitor visit = new Visitor();
parser.visitAllNodesWith((NodeVisitor)visit);
return new Web(visit.getCat(), visit.getBody(), visit.getTitle());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}