开发者

Access a file from a JAR in the same folder

开发者 https://www.devze.com 2023-04-03 22:07 出处:网络
I need to acces (create and read) a file from a JAR file (executable jar), and that file should be created in the same directory as the JAR

I need to acces (create and read) a file from a JAR file (executable jar), and that file should be created in the same directory as the JAR

I tried this.getClass().getResource("myFile") but since the jar has packages in it, it won't work..

I also tried write just File f = new File("myFile"); f.createNewFile();

and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''

how do i access a file being SURE that that file is in the SAME directory as the JAR file?

(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)开发者_开发问答


This will give you the full path to the Jar:

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:

String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();

(where the class name is Me).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号