[英]Reading in a file - java.io.FileNotFoundException
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. 该文件肯定存在于我的Assets文件夹中,并且名称正确。 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. 我在这里发现了几个类似的问题,并尝试了各种各样的事情,包括刷新项目,清理项目,使用
"levels.txt"
而不是"assets/levels.txt"
但我一直收到这个错误。
Any ideas why? 有什么想法吗?
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
捕获或声明为抛出。
In an Android project, the right way to read the content of asset files is by using the AssetManager
. 在Android项目中,阅读资产文件内容的正确方法是使用
AssetManager
。 Asset files are the files you put in the assets/
folder of your Android project. 资产文件是您放在Android项目的
assets/
文件夹中的文件。 This is mentioned briefly in the sidebar on the Accessing Resources page in the Android docs. 在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的完整文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.