简体   繁体   English

如何访问资源以进行Java读写

[英]How to access resource for reading and writing in Java

In the past I have included my 'resources' directory as a source folder (so my resources end up packaged in the final JAR), and retrieved resources using classLoader.getResource() . 过去,我将'resources'目录作为源文件夹包括在内(因此我的资源最终打包在最终的JAR中),并使用classLoader.getResource()检索了资源。 However, this only works for reading resources, not writing them. 但是,这仅适用于读取资源,而不适用于编写资源。

What is the recommended way to access resources for both reading and writing? 建议使用哪种方式访问​​资源以进行读写? I am aware of the following methods but both have disadvantages: 我知道以下方法,但两者都有缺点:

  1. System.getProperty("user.dir") - this relies on the user running the program from a particular working directory. System.getProperty("user.dir") -这依赖于从特定工作目录运行程序的用户。
  2. System.getProperty("user.home") - this relies on the resources being installed to the user's home directory. System.getProperty("user.home") -这依赖于安装到用户主目录的资源。

Try getClass().getResource(path); 尝试getClass().getResource(path);

getClass().getResource(path) uses the class loader to load the resource. getClass().getResource(path)使用类加载器加载资源。 Resources in the classpath can be loaded through this way. 可以通过这种方式加载类路径中的资源。 Suppose if you have a directory. 假设您有目录。

MyApplication 我的应用程序
1. Class1.java 1. Class1.java
2. Class1.java 2. Class1.java
3. file.txt 3. file.txt
For example to get the text file above you can access it as. 例如,要获取上面的文本文件,您可以按以下方式访问它。

File file = new File(getClass().getResource("file.txt").toString());

May I just link you to a document where you can see how to read and write properties?, the code you can grab it from there: 我可以将您链接到一个文档,在其中您可以查看如何读写属性吗?可以从此处获取代码的代码:

http://www.drdobbs.com/jvm/readwrite-properties-files-in-java/231000005 http://www.drdobbs.com/jvm/readwrite-properties-files-in-java/231000005

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM