我正在嘗試從 spring 應用程式的資源目錄中讀取檔案。
private File[] sortResources(Resource[] resources) {
assert resources != null;
File[] files = Arrays.stream(resources).sorted()
.filter(Resource::exists).filter(Resource::isFile).map(res -> {
try {
return res.getFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
).toArray(File[]::new);
for (File f : files) {
System.out.println( f.getAbsolutePath() );
}
return files;
}
使用如下:
// Read all directories inside dbdata/mongo/ directory.
Resource[] resources = resourcePatternResolver.getResources("classpath:dbdata/mongo/*");
List<File> files = sortResources(Resource[] resources);
問題出在sortResources
功能上。我想對 Resources 物件進行排序并將其轉換為 Files 物件。
我無法.toArray()
上班,因為我收到以下錯誤:
Method threw 'java.lang.ClassCastException' exception.
class org.springframework.core.io.FileSystemResource cannot be cast to class java.lang.Comparable (org.springframework.core.io.FileSystemResource is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
我也嘗試過.collect(Collectors.toList())
,但我得到了同樣的錯誤。
有人可以幫我嗎?
uj5u.com熱心網友回復:
org.springframework.core.io.FileSystemResource
顯然沒有實作該Comparable<T>
介面,因此您的呼叫會sorted
引發例外。
您可以將 a 傳遞Comparator
給,但在操作之后sorted
將呼叫簡單地移動到會更容易,因為確實實作了.sorted
map
java.io.File
Comparable
uj5u.com熱心網友回復:
正如@f1sh 已經說過的那樣,該類FileSystemResource
不是Comparable
.
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/FileSystemResource.html
要對檔案進行排序,您需要為操作提供一個Comparator
實體sorted()
。此外,由于sorted()
是有狀態的中間操作,最好將其放在后面filter()
,以減少要排序的元素。事實上,一個有狀態的操作就像sorted()
需要前一個操作的所有元素來產生一個結果。它的缺點在并行計算下非常明顯,因為包含有狀態中間操作的管道可能需要對資料進行多次傳遞,或者可能需要緩沖重要資料。
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
這是您的代碼的更新版本:
private File[] sortResources(Resource[] resources) {
assert resources != null;
File[] vetRes = new File[0];
return Arrays.stream(resources)
.filter(r -> r.exists() && r.isFile())
.map(r -> {
try {
return r.getFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.sorted(Comparator.comparing(File::getAbsolutePath))
.collect(Collectors.toList()).toArray(vetRes);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486346.html