简体   繁体   English

如何获取Jar文件路径

[英]How to get Jar File Path

I have an Verification.jar file which is checking some conditions in excel file. 我有一个Verification.jar文件,它检查excel文件中的一些条件。 I want ot create a folder called Log at the same level where that Verification.jar is present. 我想要在Verification.jar存在的同一级别创建一个名为Log 的文件夹

Thanks in Advence......... 在Advence感谢.........

EDIT 编辑

I am Having Folders as follows 我有文件夹如下

" Verification" :- Build,dist,lib,nbproject,src,Test,build.xml “验证” : - Build,dist,lib,nbproject,src,Test,build.xml

"Build" Contains Classes folder “Build”包含Classes文件夹

"dist" contains Verification.jar and Lib folder “dist”包含Verification.jar和Lib文件夹

"lib" Contains library files “lib”包含库文件

I want to find the path of Verification.jar and create the Folder called Output . 我想找到Verification.jar的路径并创建名为Output的文件夹。

If i change the drive it should create the folder at the same level where Verification.jar is present. 如果我更改了驱动器,它应该在Verification.jar所在的同一级别创建文件夹。

 String path= getClass().getResource("").getPath();

Output:--getPath:/C:/Java/jdk1.6/bin/Verification/lib/

Use URL Class.getResource(String name) method. 使用URL Class.getResource(String name)方法。

package.ClassName.class.getClassLoader().getResource("package.ClassName");

EDIT: 编辑:

Have a look at great SO thread - How to get the path of a running jar file? 看一下很棒的SO线程 - 如何获取正在运行的jar文件的路径? suggested by @Hovercraft Full Of Eels 由@Hovercraft Full Of Eels建议

The correct form is: 正确的形式是:

String directory = System.getProperty("user.dir");

If You are running a .jar file it returns the present working directory, this is the directory where the .jar is located... 如果您正在运行.jar文件,则返回当前工作目录,这是.jar所在的目录...

Note that IDEs don't run the jar file, the run the .class file where the main method is located, so when running in an IDE this method returns the projects folder 请注意,IDE不运行jar文件,运行main方法所在的.class文件,因此在IDE中运行时,此方法返回projects文件夹

PD: Sorry if I made grammar mistakes, English is not my native language. PD:对不起,如果我犯了语法错误,英语不是我的母语。

Is not the best solution, but I use this function. 不是最好的解决方案,但我使用这个功能。 The jar file must be named same as the project. jar文件的名称必须与项目相同。 Works on windows and linux. 适用于Windows和Linux。 If some can help me inprove it I will be honered. 如果有人可以帮助我证明它,我会很诚实。

public String getJarCurrentJar() {
            String[] userDir = System.getProperty("user.dir").split("\\"+System.getProperty("file.separator"));
            String appName = "";
            for (String temp : userDir) {
                appName = temp; //Get the application name/jar
            }
            return System.getProperty("user.dir") + System.getProperty("file.separator") + "dist" + System.getProperty("file.separator") + appName+".jar";
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM