Android 访问资源文件
我想访问位于类的资产下的文本文件,该类将对该文件进行一些处理并在我的活动中调用。我使用的代码是:
AssetManager assetManager = getAssets();
InputStream instream = assetManager.open("file.txt");
如果在 Activity 类中使用,则效果很好,但如何使其在普通 java 类中工作?
编辑
JamesBlack - 因为如果我传递输入流,那么下面的代码将不起作用
for (int i = 0; i < gestureNumbers.size(); i++) {
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
// possible error here
while ((line = bf.readLine()) != null) { ... }
}
即使gestureNumbers.size() > 1 那么 while 循环只执行一次,一旦读取文件一次,它就等于 null。
当以下代码可以工作但我无法在普通 java 类中打开文件时,它可以在活动类中工作,并且我不想在一个类中包含太多代码。
for (int i = 0; i < gestureNumbers.size(); i++) {
InputStream instream = assetManager.open("BSL_Word_POS.txt");
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
// possible error here
while ((line = bf.readLine()) != null) { ... }
}
I want to access a text file located under assets from a class that would do some processing on that file and is invoked in my Activity. The code I am using is:
AssetManager assetManager = getAssets();
InputStream instream = assetManager.open("file.txt");
this works fine if used in an Activity class but how to make it work in a plain java class?
Edited
JamesBlack - because if i pass the inputstream then the following code won't work
for (int i = 0; i < gestureNumbers.size(); i++) {
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
// possible error here
while ((line = bf.readLine()) != null) { ... }
}
Even if the gestureNumbers.size() > 1 then the while loop is executed only once and then it equals null once it read the file once.
When the following code works but I can't open the file in plain java class, it works in activity class and I don't want to have too much code in one class.
for (int i = 0; i < gestureNumbers.size(); i++) {
InputStream instream = assetManager.open("BSL_Word_POS.txt");
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
// possible error here
while ((line = bf.readLine()) != null) { ... }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将上下文传递给该 java 类才能访问资产文件夹。
You have to pass the context to that java class to access the asset folder.