在Java中获取文件路径时java.lang.NullPointerException(通过jar文件执行) [英] java.lang.NullPointerException while getting a filepath in Java (executing through a jar file)

查看:257
本文介绍了在Java中获取文件路径时java.lang.NullPointerException(通过jar文件执行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取文件路径(资源文件夹中的sh文件)时获取NPE。
我试过从下面的帖子中读到关于NPE i的细节,但这实际上无法解决我的问题。



什么是NullPointerException,我该如何解决?



以下是我的代码片段:

 文件absPathofBash; 

url = ClassLoader.class.getResource(assets / forbackingup.sh);
absPathofBash = new File(url.getPath());

后来我在 ProcessBuilder 中使用它,为

  ProcessBuilder pb = new ProcessBuilder(url.getPath(),param2,param3)

我也尝试直接获取绝对路径,例如

  absPathofBash = new File(assets / forbackingup.sh)。getAbsolutePath(); 

使用后一种方式,我可以处理它,但如果我创建一个 jar 然后无法找到该文件。 (虽然Jar包含相应文件夹资产中的文件)



如果有人可以帮助我,我将感激不尽。

解决方案

将代码打包为jar后,无法使用文件路径加载jar内的文件,而是将它们分类资源,你必须使用它来加载:

  this.getClass()。getClassLoader()。getResource(assets / forbackingup .SH); 

这样你加载 assets / forbackingup.sh 作为jar内的绝对路径。你也可以使用 this.getClass()。getResource()但这样路径必须相对于这个类如果你想直接获得<$ c $,方法会给你一个URL c> InputStream 你可以使用 getResourceAsStream



希望它有所帮助!


I am getting an NPE at the point of getting path of a File (an sh file in assets folder). I have tried to read about NPE i detail from the following thread, but this actually could not solve my problem.

What is a NullPointerException, and how do I fix it?

Following is my code snippet:

 File absPathofBash;

   url = ClassLoader.class.getResource("assets/forbackingup.sh");
    absPathofBash = new File(url.getPath());

Later I'm using it in a ProcessBuilder, as

ProcessBuilder pb = new ProcessBuilder(url.getPath(), param2, param3)

I've also tried getting the absolute path directly, like

absPathofBash = new File("assets/forbackingup.sh").getAbsolutePath(); 

Using the latter way, I am able to process it, but if I create a jar then the file cannot be found. (although the Jar contains the file within the respective folder assets)

I would be thankful if anyone can help me on that.

解决方案

Once you have packaged your code as a jar, you can not load files that are inside the jar using file path, instead they are class resources and you have to use this to load:

this.getClass().getClassLoader().getResource("assets/forbackingup.sh");

This way you load assets/forbackingup.sh as an absolute path inside your jar. you also can use this.getClass().getResource() but this way the path must be relative to this class path inside jar.

getResource method gives you an URL, if you want to get directly an InputStream you can use getResourceAsStream

Hope it helps!

这篇关于在Java中获取文件路径时java.lang.NullPointerException(通过jar文件执行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆