Bri*_*n J 3 java url file jackson
我已将 Java 控制台应用程序导出到 Jar 文件,但是当我运行 jar 并调用在 JSON 文件中解析的代码时,我得到一个 java.lang.IllegalArgumentException
有谁知道当我将程序作为 JAR 运行时为什么会抛出异常?当应用程序从 Eclipse 运行时,解析工作正常。
这是我执行 jar 文件并调用解析 JSON 文件的代码时输出的确切错误:
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierar
chical
at java.io.File.<init>(Unknown Source)
at gmit.GameParser.parse(GameParser.java:44)
at gmit.Main.main(Main.java:28)
Run Code Online (Sandbox Code Playgroud)
这是在我的 GameParser 类中进行解析的方式:
public class GameParser {
private static final String GAME_FILE = "/resources/game.json";
private URL sourceURL = getClass().getResource(GAME_FILE);
private int locationId;
private List<Location> locations;
private List<Item> items;
private List<Character> characters;
public void parse() throws IOException, URISyntaxException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
// read from file, convert it to Location class
Location loc = new Location();
loc = mapper.readValue(new File(sourceURL.toURI()), Location.class);
Item item = mapper.readValue(new File(sourceURL.toURI()), Item.class);
GameCharacter character = mapper.readValue(new File(sourceURL.toURI()), GameCharacter.class);
// display to console
System.out.println(loc.toString());
System.out.println(item.toString());
System.out.println(character.toString());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我项目的文件夹结构:
该调用getClass().getResource(GAME_FILE);
将返回一个相对于this
类的 URL 。如果您从 JAR 文件执行程序,它将返回一个指向 JAR 文件的 URL。
java 中的文件只能代表直接的文件系统文件,不能代表 zip/jar 档案中的文件。
要解决这个问题:
getClass().getResourceAsStream()
并使用它而不是File
s 或File
以与您现在尝试的方式相同的方式使用。