簡體   English   中英

如何在Java中獲取資源目錄的絕對路徑?

[英]How to get the absolute path for the resources directory in Java?

我正在嘗試在junit測試中找到一種獲取資源文件夾的絕對路徑的方法。

我的疑問不是在resources文件夾中獲取文件(我現在要怎么做),而是獲取resources文件夾的路徑。

例如,如果我的資源文件夾中的文件具有以下結構:

/opt/project/view/api/target/classes/
/opt/project/view/api/target/classes/file_in_resources.txt

我想獲得位置/opt/project/view/api/target/classes/而不使用類似以下的丑陋內容:

URL location = this.getClass().getResource("/file_in_resources.txt");
String path = location.getPath();
String rightPath = path.substring(0, path.lastIndexOf("/"));

這個想法是有一個像this.getClass().getResourcesPath()這樣的方法,但是這種方法不存在。

怎么做?

如果您的測試類位於同一資源文件夾中,則可以嘗試:

URL location = TestClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getPath();
String rightPath = path.substring(0, path.lastIndexOf("/"));

如果資源文件夾不相同,則可以根據其相對位置,以“測試類”的位置(使用上面的代碼獲得)為參考,導航到該文件夾​​。

String adjustedPath = rightPath+"/resources";

如果一個人應該“有這個問題”,那么關於贊成與反對的爭論可能會進行很長的哲學討論。 但是,如果您也像我一樣碰到它,那么,如果要使用當前的Java風格 ,這可能是一條路(假設: file_in_resources.txt位於適當的Unittest標准文件夾src / test中/資源):

private String readFileFromResourcesAsString(String fileName) throws IOException {
    Path filePath = Paths.get("./src/test/resources/yourCustomPathHere/" + fileName);
    return Files.lines(filePath).collect(Collectors.joining());        
}

如果您確實要堅持使用view / api / target / classes /文件夾,則可以將該Paths.get-statement與java.net.URI一起使用(例如已經提到的Chetan Jadhav CD ):

Paths.get(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());

該解決方案利用了圍繞NIO.2的最新Java-API(請參見此處的oracle教程 ),例如

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

以及一些Java 8流API部分,以將Files內容讀入字符串(您可以根據需要更改此部分:))。

Paths.get(".")

這是關鍵-無論您使用什么操作系統(Windows,Linux,MacOS),它都可以透明地為您提供當前工作目錄。

如果您是Spring用戶,那么整個過程就更加容易了! 在這里看到答案

如果您處於單元測試的環境中,那么直接引用文件就沒問題,因為您知道文件在哪里而且不會在任何地方運行。 您可以獲取文件的url,然后使用“ Path在文件夾結構中向上導航,直到擁有正確的文件夾。

final URL location = this.getClass().getResource("/file_in_resources.txt");
final Path path = Paths.get(location.getPath());
final String folder = path.getParent() //getParent().getParent()...
                          .toString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM