[英]Access a file from a JAR in the same folder
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 我需要从JAR文件(可执行jar)访问(创建和读取)文件,并且该文件应该在与JAR相同的目录中创建
I tried this.getClass().getResource("myFile")
but since the jar has packages in it, it won't work.. 我试过
this.getClass().getResource("myFile")
但由于jar中有包,它不起作用..
I also tried write just File f = new File("myFile"); f.createNewFile();
我也试过写
File f = new File("myFile"); f.createNewFile();
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 -.-'' 如果我从终端执行JAR,那么这是有效的,但如果我通过双击它来执行JAR,那么该文件将在我的主目录中创建 - .-''
how do i access a file being SURE that that file is in the SAME directory as the JAR file? 我如何访问一个文件,确保该文件作为JAR文件在SAME目录中?
(of course also getting the jar absolute path would do the trick since i can get the parent folder from it) (当然也获得jar绝对路径会起作用,因为我可以从中获取父文件夹)
This will give you the full path to the Jar: 这将为您提供Jar的完整路径:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
EDIT: sorry, was in javascript mode when I wrote that :). 编辑:对不起,当我写这个:)时,是在JavaScript模式下。 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
). (班级名称是
Me
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.