过去我将'resources'目录作为源文件夹包含在内(因此我的资源最终打包在最终的JAR中),并使用classLoader.getResource()
检索资源。但是,这仅适用于阅读资源,而不是编写资源。
读取和写入资源的推荐方法是什么?我知道以下方法,但都有缺点:
System.getProperty("user.dir")
- 这取决于从特定工作目录运行程序的用户。System.getProperty("user.home")
- 这取决于安装到用户主目录的资源。答案 0 :(得分:1)
尝试getClass().getResource(path);
getClass().getResource(path)
使用类加载器加载资源。可以通过这种方式加载类路径中的资源。
假设你有一个目录。
所有MyApplication
访问
1. Class1.java
2. Class1.java
3. file.txt
例如,要获取上面的文本文件,您可以将其作为。
File file = new File(getClass().getResource("file.txt").toString());
答案 1 :(得分:1)
我可以将您链接到一个文档,您可以在其中查看如何读取和写入属性吗?您可以从那里获取代码:
http://www.drdobbs.com/jvm/readwrite-properties-files-in-java/231000005
此致