读入文件 - java.io.FileNotFoundException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17638063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading in a file - java.io.FileNotFoundException
提问by Zippy
public void loadFile(int level){
try {
//Create new file
levelFile = new File("assets/levels.txt");
fis = new FileInputStream(levelFile);
isr = new InputStreamReader(fis);
reader = new BufferedReader(isr);
//Code to read the file goes here
Using this code, however, I keep getting the above error (java.io.FileNotFoundException
).
但是,使用此代码,我不断收到上述错误 ( java.io.FileNotFoundException
)。
The file definitely exists in my Assets folder and has the correct name. I've found a couple of similar questions on here and have tried various things including refreshing the project, cleaning the project, using "levels.txt"
instead of "assets/levels.txt"
but I keep getting this error.
该文件肯定存在于我的 Assets 文件夹中并且具有正确的名称。我在这里发现了几个类似的问题,并尝试了各种方法,包括刷新项目、清理项目、使用"levels.txt"
而不是,"assets/levels.txt"
但我一直收到此错误。
Any ideas why?
任何想法为什么?
回答by Azad
Because you're dealing with outside the package, getResource()
will be the best solution for your problem:
因为您正在处理外包装,所以getResource()
将是您问题的最佳解决方案:
URL url = getClass().getResource("/assets/levels.txt");
File f = new File(url.toURI());
//....
Or you can directly get the input stream using getResourceAsStream()
method :
或者您可以使用getResourceAsStream()
方法直接获取输入流:
InputStream is= getClass().getResourceAsStream("/assets/levels.txt");
isr = new InputStreamReader(is);
It's better since you don't have to use FileInputStream.
更好,因为您不必使用FileInputStream。
Note that URISyntaxException
must be caught with FileNotFoundException
or declared to be thrown.
请注意,URISyntaxException
必须被捕获FileNotFoundException
或声明为抛出。
回答by janos
In an Android project, the right way to read the content of asset files is by using the AssetManager
. Asset files are the files you put in the assets/
folder of your Android project. This is mentioned briefly in the sidebar on the Accessing Resourcespage in the Android docs.
在 Android 项目中,读取资产文件内容的正确方法是使用AssetManager
. 资产文件是您放在assets/
Android 项目文件夹中的文件。Android 文档中访问资源页面的侧边栏中简要提到了这一点。
In particular, you can open the file assets/levels.txt
and create a BufferedReader
like this:
特别是,您可以打开文件assets/levels.txt
并创建BufferedReader
如下所示的文件:
InputStream stream = context.getAssets().open("levels.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
Notice that the argument of the open
call is simply levels.txt
, not assets/levels.txt
.
请注意,open
调用的参数很简单levels.txt
,不是assets/levels.txt
。
For more details see the full docs of AssetManager.
有关更多详细信息,请参阅AssetManager的完整文档。