从jar文件中读取文件,使用netbeans生成jar

时间:2015-08-03 11:19:45

标签: java maven netbeans netbeans-7

我有一个java项目应该读取外部文件夹中的文件。我在类中将文件路径指定为“../FolderName”。但是如果我从这个项目生成一个jar文件,它就无法读取该文件。在这种情况下定义文件夹路径的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

您应该使用 var json = { "868": { "header": "New limited", "lite": "1337 Gaming Headset", "icon": "", "items": { "Stock": "1,337", "Price": "R$750" }, "extra": { "product": 25355494 }, "url": "", "id": 868, "added": 1438542256903 }, "869": { "header": "New Face", "lite": "Furious George", "icon": "", "items": { "Price": "R$200" }, "extra": { "product": 25355932 }, "url": "", "id": 869, "added": 1438543456863 }, "870": { "header": "Almost sold out", "lite": "1337 Gaming Headset", "icon": "", "items": { "Stock": "1,337", "Remaining": "133", "Price": "R$750" }, "extra": { "product": 25355494 }, "url": "", "id": 870, "added": 1438544588831 }, "871": { "header": "Sold out", "lite": "1337 Gaming Headset", "icon": "", "items": { "Price": "R$750" }, "extra": {}, "url": "", "id": 871, "added": 1438544704049 }, "872": { "header": "New Hat", "lite": "Elite Spy Eye", "icon": "", "items": { "Price": "R$250" }, "extra": { "product": 25356879 }, "url": "", "id": 872, "added": 1438545677167 } } var keys = Object.keys(json); var last = keys[keys.length - 1]; document.write('"' + last + '": ' + JSON.stringify(json[last]));

它从java.lang.Class.getResourceAsStream(String)内部读取文件。

示例:

JAR

一个很好的参考:How to read a file from a jar file?

答案 1 :(得分:0)

将绝对路径传递给代码(jar)作为程序参数的正确方法。

java -jar myjar.jar abs_path

然后,您可以访问类的main()方法中的绝对路径(在JAR的manifest.mf文件中提到),如下所示:

String filePath = args[0];

答案 2 :(得分:0)

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/classpath/toyourfile");
相关问题