如何从java类中读取文件,两者都在同一个jar中 [英] How to read a file from a java class, both are in the same jar

查看:125
本文介绍了如何从java类中读取文件,两者都在同一个jar中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jar中有以下结构

I have following structure in jar


myjar.jar - > com - > MYProgram.class

myjar.jar -> com -> MYProgram.class

       -> file.txt


在MYProgram中我想做的事:

In MYProgram i am trying to do:

getClass().getResourceAsStream("../file.txt")

当我尝试读取输入流时,我收到NullpointerException ..

I am getting NullpointerException when i try to read the inputstream..

哪里出错了?

推荐答案

使用

getClass().getResourceAsStream("/file.txt")

getClass().getClassLoader().getResourceAsStream("file.txt")

ClassLoader.getResourceAsStream 总是采用绝对资源名称。)

(ClassLoader.getResourceAsStream always takes an "absolute" resource name.)

我不相信导航目录层次结构在 getResourceAsStream 中工作 - 路径要么必须是相对于给定的类,要么没有导航备份树,或者它必须是绝对的开始。

I don't believe navigating up the "directory hierarchy" works in getResourceAsStream - the path either has to be relative to the given class but without navigating back up the tree, or it has to be absolute to start with.

这篇关于如何从java类中读取文件,两者都在同一个jar中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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