如何使用 URI 從資源檔案夾的子檔案夾中讀取檔案
How to read files from the sub folder of resource folder.
我在資源檔案夾中有一些 json 檔案,例如:
src
main
resources
jsonData
d1.json
d2.json
d3.json
現在我想在我的課上讀這個
src
main
java
com
myFile
classes
這就是我正在嘗試的。
File[] fileList = (new File(getClass().getResource("/jaonData").toURI())).listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
// my operation of Data.
}
}
我的東西作業正常,但我得到的問題是我不想使用toURI它,因為它正在失敗。
uj5u.com熱心網友回復:
您可能沒有使用 Spring Boot,因此如何在 spring boot 中從 resolurces 檔案中讀取檔案夾:從 Jar 運行時出現錯誤對您沒有多大幫助。
我將從對該問題的評論中重復自己:
JAR 檔案中的所有內容都不是檔案,不能使用 , 等訪問
File。FileInputStream沒有官方機制可以訪問 JAR 檔案中的目錄。
幸運的是,有一種非官方的方式,它利用了您可以將 JAR 檔案作為單獨的檔案系統打開的事實。
這是一種適用于基于檔案的檔案系統和 JAR 檔案中的資源的方法:
private void process() throws IOException {
Path classBase = getClassBase();
if (Files.isDirectory(classBase)) {
process(classBase);
} else {
// classBase is the JAR file; open it as a file system
try (FileSystem fs = FileSystems.newFileSystem(classBase, getClass().getClassLoader())) {
Path root = fs.getPath("/");
return loadFromBasePath(root);
}
}
}
private Path getClassBase() {
ProtectionDomain protectionDomain = getClass().getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
URL location = codeSource.getLocation();
try {
return Paths.get(location.toURI());
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
private void processRoot(Path root) throws IOException {
// use root as if it's either the root of the JAR, or target/classes
// for instance
Path jsonData = root.resolve("jsonData");
// Use Files.walk or Files.newDirectoryStream(jsonData)
}
如果你不喜歡使用ProtectionDomain,你可以使用另一個小技巧,利用每個類檔案都可以作為資源讀取的事實:
private Path getClassBase() {
String resourcePath = '/' getClass().getName().replace('.', '/') ".class";
URL url = getClass().getResource(resourcePath);
String uriValue = url.toString();
if (uriValue.endsWith('!' resourcePath)) {
// format: jar:<file>!<resourcePath>
uriValue = uriValue.substring(4, uriValue.length() - resourcePath.length() - 1);
} else {
// format: <folder><resourcePath>
uriValue = uriValue.substring(0, uriValue.length() - resourcePath.length());
}
return Paths.get(URI.create(uriValue));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511793.html
標籤:爪哇春天弹簧靴文件
