Java JAR 找不到文件 [英] Java JAR can't find file

查看:62
本文介绍了Java JAR 找不到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 eclipse 中运行一个程序,该程序引用了程序源文件夹中的一个文件.但是,当我将程序导出到可运行的 JAR 中时,该程序似乎找不到该文件.从本质上讲,该程序在 eclipse 中运行良好,但当它是独立程序时就不行了.

I am running a program in eclipse that references a file in the program's source folder. However, when I export the program into a runnable JAR, the program cannot seem to find the file. Essentially, the program works perfect in eclipse but doesn't do so when it's a standalone program.

我附上了一张我如何在程序中引用文件的照片.

I've attached a photo of how I reference the file in the program.

推荐答案

一旦它在 jar 中,您就无法使用 new File() 找到它——它现在是一个类路径资源.您需要使用 this.getClass().getResourceAsStream("/TestFileFolder/TRANSFER.xls"); (或者,如果您的方法是静态的,则需要使用 className.class 代替 getClass()).

Once it's in the jar, you can't find it using new File() -- it's now a class path resource. You need to use this.getClass().getResourceAsStream("/TestFileFolder/TRANSFER.xls"); (or, if your method is static, you need to use the className.class in place of getClass()).

这实际上是一个功能——如果出于任何原因您需要更改 TRANSFER.xls 资源,您可以通过在类路径中隐藏它来实现,而无需重新打包 jar.

this is actually a feature -- if for any reason you need to change the TRANSFER.xls resource, you can do so by shadowing it in the classpath without repacking the jar.

这篇关于Java JAR 找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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