Java类读取一个Yaml Inside Jar [英] Java Class Read a Yaml Inside Jar
问题描述
我正在尝试从jar中的另一个类读取jar中的文件。但是我不断得到同样的错误:Caught:尝试读取指标时类java.io.FileNotFoundException:metrics.yml
I am trying to read a file inside my jar from another class inside the jar. However I am continually getting the same error: Caught: class java.io.FileNotFoundException while attempting to read metrics: metrics.yml
起初我的代码做了类似的事情这个,假设它来自类的路径:
At first I had my code do something like this, assuming it was from the path of the class:
String yamlPath = ".." + File.separator + ".." + File.separator + ".." + File.separator + ".." + File.separator + "myYaml.yml";
InputStream in = new FileInputStream(new File(yamlPath));
InputStreamReader isr = new InputStreamReader(in);
BufferedReader input = new BufferedReader(isr);
yamlObj = (HashMap) javaYAML.load(input);
我也这样做,假设它可能从jar的底部开始:
I also did this assuming it might take the path from the base of the jar:
String yamlPath = "myYaml.yml";
InputStream in = new FileInputStream(new File(yamlPath));
InputStreamReader isr = new InputStreamReader(in);
BufferedReader input = new BufferedReader(isr);
yamlObj = (HashMap) javaYAML.load(input);
然后我注意到这个帖子如何从Java中读取jar文件?并发现我在路径前需要一个/。我也使用斜杠尝试了上述两种方法。
I then noticed this thread How to read a file from jar in Java? and found out that I needed a "/" before my path. I tried both methods above using the slash as well.
String yamlPath = File.seperator + ".." + File.separator + ".." + File.separator + ".." + File.separator + ".." + File.separator + "myYaml.yml";
OR
String yamlPath = File.seperator + "myYaml.yml";
我现在完全失去了对此错误的处理方法。我有没有得到关于罐子结构的东西?为什么我的文件找不到。提前感谢您提供任何帮助/信息。
I am completely lost on what to do about this error now. Is there something I am not getting about the jar structure? Why can my file not be found. Thanks in advance for any help / information.
抱歉,我忘了提到它在JAR中的位置:
该课程位于以下路径:com /a/b/c/myclass.class
yaml位于以下路径中:myYaml.yml
Sorry, I forgot to mention where it is in the JAR: The class is in the following path: com/a/b/c/myclass.class The yaml is in the following path: myYaml.yml
推荐答案
Jar中的文件不再是文件,使用此更改inputStream创建
File inside Jar is no longer a File, Change inputStream creation with this
InputStream in = YourClass.class.getResourceAsStream("myYaml.yml");
假设您的 .yml
文件位于root jar
Assuming your .yml
file is at root of jar
这篇关于Java类读取一个Yaml Inside Jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!