如何在不指定绝对路径的情况下从另一个 java 包读取文件(例如 txt 文件)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3887138/
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
How to read a file (e.g txt file) from another java package withouth specifying the absolute path?
提问by Scicare
I have stored non-java files in a package. I want to read files from this package without specifying the absolute path to the file(e.g C:\etc\etc...). How should I do this?
我将非 java 文件存储在一个包中。我想从这个包中读取文件而不指定文件的绝对路径(例如 C:\etc\etc...)。我该怎么做?
采纳答案by Pablo Fernandez
For example:
例如:
MyClass.class.getResourceAsStream("file.txt");
Will open file.txt
if it's in the same package that MyClass
file.txt
如果它在同一个包裹中,将打开MyClass
Also:
还:
MyClass.class.getResourceAsStream("/com/foo/bar/file.txt");
Will open file.txt
on package com.foo.bar
将file.txt
在包装上打开com.foo.bar
Good luck! :)
祝你好运!:)
回答by pf_miles
First, ensure that the package in which your files contained is in your app's classpath.. Though your didnt specifying the path of the files, you still have to obtain the files' paths to read them.Your know all your files' names and package name(s)? If so, your could try this to obtain a url of your file:
首先,确保您的文件所在的包在您的应用程序的类路径中。虽然您没有指定文件的路径,但您仍然需要获取文件的路径才能读取它们。您知道所有文件的名称和包姓名?如果是这样,您可以尝试使用此方法获取文件的 url:
public class Test {
public static void main(String[] args) throws Exception {
URL f = Test.class.getClassLoader().getResource("resources/Test.txt");
System.out.println(f);
}
}
the code above obtains the url of file 'Test.txt' in another package named 'resources'.
上面的代码在另一个名为“resources”的包中获取文件“Test.txt”的url。