无法访问res文件夹? [英] Cannot access res folder?

查看:215
本文介绍了无法访问res文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java编程问题我想要一些帮助!



我有一个单独的包中的类文件(而不是默认包)。我正在尝试从我的res文件夹访问一个文件。我已经把它添加为一个类文件夹(使用属性 - >库 - >添加类文件夹)在我的类中,我有以下代码:

 code> InputStream IS = getClass()。getResourceAsStream(mytextfile.txt); 

然而,它不起作用,我拥有所有正确的导入和一切,但我只是不能让它工作...(当我尝试使用IS时给出空指针异常)



我认为它与使用单独的包有关,因为我有另一个程序使用默认包,它工作正常...



我想要一种方式,我可以访问该文件,当我使用Eclipse,当我将其导出为.jar。



提前感谢您的帮助!



编辑:我试过使用/res/mytextfile.txt,但是不起作用。

解决方案

getClass ).getResource 将查找相对于类存在的位置的命名资源。



所以如果类存在于包 foo.bar getResource 将查找 foo / bar / mytextfile.txt (前缀为class,classloader的c lass path context ...)



相反,请尝试使用相对路径,例如

  InputStream IS = getClass()。getResourceAsStream(/ mytextfile.txt); 

  InputStream IS = getClass()。getResourceAsStream(/ res / mytextfile.txt); 

假设资源目录称为 res 并存在于默认包


I have a Java programming problem I would like some help on!

I have my class files in a separate package (not default package). I am trying to access a file from my res folder. I have added it as a class folder (using properties --> libraries --> add class folder) In my class I have the following code:

InputStream IS = getClass().getResourceAsStream("mytextfile.txt");

However it doesn't work, I have all the proper imports and everything but I just can't get it to work... (gives null pointer exception when I try to use the IS)

I think it has something to do with using a separate package, because I have another program that uses the default package and it works fine...

I want a way where I can access the file both when I'm using Eclipse and when I have it exported as a .jar.

Thanks in advance for your help!

EDIT: I have tried using /res/mytextfile.txt but that doesn't work either...

解决方案

getClass().getResource will look for the named resource relative to the location that the class exists.

So if the class exists in the package foo.bar, getResource will look in foo/bar/mytextfile.txt (prefixing the classes, classloader's class path context...)

Instead, try using a relative path, such as

InputStream IS = getClass().getResourceAsStream("/mytextfile.txt");

or

InputStream IS = getClass().getResourceAsStream("/res/mytextfile.txt");

Assuming that the resource directory is called res and exists under the default package

这篇关于无法访问res文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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