【发布时间】:2019-08-17 21:22:12
【问题描述】:
(我是java新手,请谅解)
我正在用 java 编写一个需要配置文件的应用程序,配置文件是一个 json 文件,我需要打开它并读取它的内容,但无论我如何尝试我都无法做到,我已经做了几个小时的查找在互联网上,但我找不到工作方式
我尝试使用我的 POM.xml 创建资源文件夹,然后使用 .getResource() 但这似乎不起作用
我的 java
public class MusicOrganizer {
public static String configURL = "assets/config.json";
public static String configSource;
public static void main(String[] args) {
try {
configSource = MO.getFileFromResources(configURL);
} catch (IOException e) {
// This isn't what is going wrong
System.out.println("Error reading config file!\n" + e + "\nDisplaying error screen...");
errorScreen.main("Error Reading Config", "Try redownloading the application.","ERC_001");
return;
}
}
private String getFileFromResources(String fileName) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file is not found!"); // this is what is going wrong
} else {
return printFile(new File(resource.getFile()));
}
}
private static String printFile(File file) throws IOException {
if (file == null) throw new IllegalArgumentException("file is not found!");
String source = "";
try (FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
source += line;
}
return source;
}
}
}
我在其中创建“资源文件夹”的 POM.xml
<build>
<resources>
<resource>
<directory>assets</directory>
</resource>
</resources>
</build>
请告诉我我做错了什么,我想让我的 java 文件(以压缩的 .jar 形式)读取“config.json”文件中的内容。
我使用的是 NetBeans 11.1,java 版本“12.0.2”2019-07-16, Java(TM) SE 运行时环境 (build 12.0.2+10), Java HotSpot(TM) 64 位服务器 VM(内部版本 12.0.2+10,混合模式,共享)和 MacBook Pro
我的目录路径:
>ROOT
>nb-configuration.xml
>nbactions.xml
>pom.xml
>src
>main
>java
>com
>[my name]
>musicorganizer
[java files]
>JSON
[java files]
>resources
config.json
>test
>java
[nothing here]
>target
[Stuff]
【问题讨论】:
-
如果它在 JAR 中,则需要使用 getResourceAsStream():stackoverflow.com/questions/20504014/… 和 stackoverflow.com/questions/3861989/…
-
无法通过通常的文件 API 读取资源(例如
File)。要读取资源的内容,您需要通过#getResource(String)返回的URL或直接通过#getResourceAsStream(String)打开一个InputStream。此外,不需要添加资源根目录——只需使用标准的默认目录(即src/main/resources)。至于找不到资源,你的目录结构是什么样的? -
我添加了我的目录结构
-
您首先需要明确自己想要什么。您想要一个只读的、不可编辑的资源嵌入到您的构建生成的 jar 文件中,还是想要一个用户或程序可以编辑以更改配置的外部、可编辑的配置文件?如果是前者,请使用位于 src/main/resources 中的资源,并使用
MyClass.class.getResourceAsStream("/thefile.json")读取它。否则,不要将其作为资源。例如,将其设为位于用户主目录下的文件,并使用文件 IO 对其进行读/写。 -
那么它应该是一个资源。它应该是文件系统上的普通旧文件。不要尝试使用 Maven 将其嵌入到 jar 中,因为您不希望这样。