我正在尝试读取目录下所有子目录中的文件。我已经编写了逻辑,但是由于某些原因它会将每个文件读取两次。
为了测试我的实现,我创建了一个包含三个子目录的目录,每个子目录中有10个文档,总共应该有30个文档。
以下是我用于测试正确读入文档的代码:
当我运行测试用例时,我发现
在我的代码中,我在哪里读取了文档两次?
为了测试我的实现,我创建了一个包含三个子目录的目录,每个子目录中有10个文档,总共应该有30个文档。
以下是我用于测试正确读入文档的代码:
String basePath = "src/test/resources/20NG";
Driver driver = new Driver();
List<Document> documents = driver.readInCorpus(basePath);
assertEquals(3 * 10, documents.size());
Driver#readInCorpus
的代码如下:
public List<Document> readInCorpus(String directory)
{
try (Stream<Path> paths = Files.walk(Paths.get(directory)))
{
return paths
.filter(Files::isDirectory)
.map(this::readAllDocumentsInDirectory)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.emptyList();
}
private List<Document> readAllDocumentsInDirectory(Path path)
{
try (Stream<Path> paths = Files.walk(path))
{
return paths
.filter(Files::isRegularFile)
.map(this::readInDocumentFromFile)
.collect(Collectors.toList());
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.emptyList();
}
private Document readInDocumentFromFile(Path path)
{
String fileName = path.getFileName().toString();
String outputClass = path.getParent().getFileName().toString();
List<String> words = EmailProcessor.readEmail(path);
return new Document(fileName, outputClass, words);
}
当我运行测试用例时,我发现
assertEquals
失败了,因为检索到了60个文档,而不是30个,这是错误的。当我进行调试时,所有文档都被插入到列表中一次,然后按完全相同的顺序再次插入。在我的代码中,我在哪里读取了文档两次?
Paths.walk
会自动包含子目录中的文件。谢谢! - Cache Staheli