在java中使用相对路径打开资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/573679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
open resource with relative path in java
提问by Giancarlo
In my Java app I need to get some files and directories.
在我的 Java 应用程序中,我需要获取一些文件和目录。
This is the program structure:
这是程序结构:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass
loads the resourcesloader class which will load my resources (directory and file).
guiclass
加载将加载我的资源(目录和文件)的资源加载器类。
As to the file, I tried
至于文件,我试过了
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
in order to get the real path, but this way does not work.
为了得到真正的路径,但这种方式行不通。
I have no idea how to do the directory.
我不知道如何做目录。
采纳答案by jonathan.cone
Supply the path relative to the classloader, not the class you're getting the loader from. For instance:
提供相对于类加载器的路径,而不是您从中获取加载器的类。例如:
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
回答by RichH
Doe the following work?
下面的工作吗?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
是否有理由不能指定包括包在内的完整路径?
回答by Tom Hawtin - tackline
resourcesloader.class.getClass()
Can be broken down to:
可以分解为:
Class<resourcesloader> clazz = resourceloader.class;
Class<Class> classClass = clazz.getClass();
Which means you're trying to load the resource using a bootstrap class.
这意味着您正在尝试使用引导程序类加载资源。
Instead you probably want something like:
相反,您可能想要这样的东西:
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
If only javac warned about calling static methods on non-static contexts...
如果只有 javac 警告在非静态上下文中调用静态方法...
回答by nbeyer
When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.
在类上使用“getResource”时,根据类所在的包解析相对路径。在类加载器上使用“getResource”时,根据根文件夹解析相对路径。
If you use an absolute path, both 'getResource' methods will start at the root folder.
如果您使用绝对路径,则两个 'getResource' 方法都将从根文件夹开始。
回答by Johnny
I had problems with using the getClass().getResource("filename.txt")
method.
Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'
. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:
我在使用该getClass().getResource("filename.txt")
方法时遇到了问题。阅读 Java 文档说明后,如果您的资源与您尝试从中访问资源的类不在同一个包中,那么您必须为它提供以'/'
. 推荐的策略是将您的资源文件放在根目录中的“resources”文件夹下。因此,例如,如果您具有以下结构:
src/main/com/mycompany/myapp
then you can add a resources folder as recommended by maven in:
然后您可以按照 maven 的建议添加一个资源文件夹:
src/main/resources
furthermore you can add subfolders in the resources folder
此外,您可以在资源文件夹中添加子文件夹
src/main/resources/textfiles
and say that your file is called myfile.txt
so you have
并说你的文件被调用,myfile.txt
所以你有
src/main/resources/textfiles/myfile.txt
Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package
, and you want to access the myfile.txt
file from your resource folder. Some say you need to give the:
现在这是愚蠢的路径问题出现的地方。假设您的 中有一个类com.mycompany.myapp package
,并且您想myfile.txt
从资源文件夹访问该文件。有人说你需要提供:
"/main/resources/textfiles/myfile.txt" path
or
或者
"/resources/textfiles/myfile.txt"
both of these are wrong. After I ran mvn clean compile
, the files and folders are copied in the:
这两个都是错误的。我运行后mvn clean compile
,文件和文件夹被复制到:
myapp/target/classes
folder. But the resources folder is not there, just the folders in the resources folder. So you have:
文件夹。但是资源文件夹不存在,只有资源文件夹中的文件夹。所以你有了:
myapp/target/classes/textfiles/myfile.txt
myapp/target/classes/com/mycompany/myapp/*
so the correct path to give to the getClass().getResource("")
method is:
所以给getClass().getResource("")
方法的正确路径是:
"/textfiles/myfile.txt"
here it is:
这里是:
getClass().getResource("/textfiles/myfile.txt")
This will no longer return null, but will return your class.
I hope this helps somebody. It is strange to me, that the "resources"
folder is not copied as well, but only the subfolders and files directly in the "resources"
folder. It would seem logical to me that the "resources"
folder would also be found under "myapp/target/classes"
这将不再返回 null,但会返回您的类。我希望这对某人有帮助。我很奇怪,"resources"
文件夹也没有复制,而是直接复制了文件夹中的子文件夹和文件"resources"
。对我来说,该"resources"
文件夹也可以在下面找到似乎合乎逻辑"myapp/target/classes"
回答by Vikram
@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
@GianCarlo:您可以尝试调用 System 属性 user.dir ,这将为您提供 Java 项目的根目录,然后将此路径附加到您的相对路径,例如:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\path \to\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
回答by E-rich
In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):
为了为那些不像其他人那么快地掌握它的人提供更多信息,我想提供我的场景,因为它的设置略有不同。我的项目是使用以下目录结构设置的(使用 Eclipse):
Project/ src/ // application source code org/ myproject/ MyClass.java test/ // unit tests res/ // resources images/ // PNG images for icons my-image.png xml/ // XSD files for validating XML files with JAXB my-schema.xsd conf/ // default .conf file for Log4j log4j.conf lib/ // libraries added to build-path via project settings
I was having issues loading my resources from the resdirectory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the resdirectory to the build-pathand then access the resource via:
我在从res目录加载我的资源时遇到问题。我希望我的所有资源都与我的源代码分开(仅用于管理/组织目的)。所以,我必须做的是将res目录添加到构建路径,然后通过以下方式访问资源:
static final ClassLoader loader = MyClass.class.getClassLoader();
// in some function
loader.getResource("images/my-image.png");
loader.getResource("xml/my-schema.xsd");
loader.getResource("conf/log4j.conf");
NOTE:The /
is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String)instead of Class.getResource(String).
注:该/
从资源字符串的开头省略,因为我使用 ClassLoader.getResource方法,(串),而不是Class.getResource(字符串)。
回答by manocha_ak
Going with the two answers as mentioned above. The first one
与上面提到的两个答案一起使用。第一个
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
Should be one and same thing?
应该是一回事吗?
回答by Paul Mira
For those using eclipse + maven. Say you try to access the file images/pic.jpg
in src/main/resources
. Doing it this way :
对于那些使用 eclipse + maven 的人。假设您尝试访问该文件images/pic.jpg
在src/main/resources
。这样做:
ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());
is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources
folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.
完全正确,但可能导致空指针异常。似乎 eclipse 无法立即将 Maven 目录结构中的文件夹识别为源文件夹。通过src/main/resources
从项目的源文件夹列表中删除文件夹并将其放回(项目>属性>java构建路径>源>删除/添加文件夹),我能够解决这个问题。
回答by Alferd Nobel
I made a small modification on @jonathan.cone's one liner ( by adding .getFile()
) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
我对@jonathan.cone 的单行代码做了一个小的修改(通过添加.getFile()
)以避免空指针异常,并设置了数据目录的路径。这是对我有用的:
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();