We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
使用
ClassLoader#getResource()
或getResourceAsStream()
从类路径获取它们作为URL
或InputStream
。或者,如果它与当前类在同一个包中,您也可以通过以下方式获取它:
保存是一个故事。如果文件位于 JAR 文件中,这将不起作用。如果您可以确保文件已展开且可写,请将
URL
从getResource()
转换为File
。然后,您可以构造一个
FileOutputStream
与它一起。相关问题:
getResourceAsStream()
与FileInputStream
Use
ClassLoader#getResource()
orgetResourceAsStream()
to obtain them asURL
orInputStream
from the classpath.Or if it is in the same package as the current class, you can also obtain it as follows:
Saving is a story apart. This won't work if the file is located in a JAR file. If you can ensure that the file is expanded and is writable, then convert the
URL
fromgetResource()
toFile
.You can then construct a
FileOutputStream
with it.Related questions:
getResourceAsStream()
versusFileInputStream
如果您的类是从文件系统加载的,您可以尝试以下操作。
要获取该路径中的文件,您可以使用
You can try the following provided your class is loaded from a filesystem.
To get a file in that path you can use
一般情况下你不能。从类加载器加载的资源可以是任何内容:目录中的文件、嵌入到 jar 文件中的文件,甚至是通过网络下载的文件。
In the general case you cannot. Resources loaded from a classloader can be anything: files in directories, files embedded in jar files or even downloaded over the network.
new File(".").getAbsolutePath() + "relative/path/to/your/files";
new File(".").getAbsolutePath() + "relative/path/to/your/files";
这是 Peter 响应的扩展:
如果您希望文件与当前类位于同一类路径中(示例:project/classes):
如果您希望文件位于不同的类路径中(示例:progect/test-classes),只需替换
this.getClass()
与类似TestClass.class
的内容。从类路径读取属性:
将属性写入类路径:
在类路径上创建文件对象:
This is an expansion on Peter's response:
If you want the file in the same classpath as the current class (Example: project/classes):
If you want the file in a different classpath (Example: progect/test-classes), just replace
this.getClass()
with something likeTestClass.class
.Read Properties from Classpath:
Write Properties to Classpath:
Create the File Object on the Classpath:
根据系统属性文档,您可以将其作为“java.class.path”属性访问:
According to system properties documentation, you can access this as the "java.class.path" property: