android - 从 Assets 中读取文件

标签 android

public class Utils {
    public static List<Message> getMessages() {
        //File file = new File("file:///android_asset/helloworld.txt");
        AssetManager assetManager = getAssets();
        InputStream ims = assetManager.open("helloworld.txt");    
     }
}

我正在使用此代码尝试从 Assets 中读取文件。我尝试了两种方法来做到这一点。首先,当使用 File 我收到 FileNotFoundException,当使用 AssetManager getAssets() 方法时无法识别。 这里有什么解决办法吗?

最佳答案

这是我在缓冲阅读扩展/修改以满足您的需求的 Activity 中所做的

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt")));

    // do reading, usually loop until end of file reading  
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

编辑:如果您的问题是关于如何在 Activity 之外进行操作,我的回答可能毫无用处。如果您的问题只是如何从 Assets 中读取文件,那么答案就在上面。

更新:

要打开指定类型的文件,只需在 InputStreamReader 调用中添加类型,如下所示。

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt"), "UTF-8")); 

    // do reading, usually loop until end of file reading 
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

编辑

正如@Stan 在评论中所说,我给出的代码不是总结行。 mLine 每次通过都会被替换。这就是我写 //process line 的原因。我假设该文件包含某种数据(即联系人列表),并且每一行都应该单独处理。

如果您只是想在不进行任何处理的情况下加载文件,则必须在每次遍历时使用 StringBuilder() 总结 mLine 并附加每个遍历。

另一个编辑

根据@Vincent 的评论,我添加了 finally block 。

另外请注意,在 Java 7 及更高版本中,您可以使用 try-with-resources 来使用最新 Java 的 AutoCloseableCloseable 功能.

上下文

@LunarWatcher 在评论中指出 getAssets()context 中的 class。因此,如果您在 activity 之外调用它,则需要引用它并将上下文实例传递给 Activity。

ContextInstance.getAssets();

@Maneesh 的回答对此进行了解释。因此,如果这对您有用,请支持他的回答,因为是他指出了这一点。

关于android - 从 Assets 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9544737/

相关文章:

java - Android 中 JUnit 的替代方案

android - Seekbar在媒体播放器实现中没有进展

android - 是否可以在 android 上训练 tensorflow?

android - 为 ListView 的特定子项应用 android 选择器,并在同一列表项中的其他子项上禁用选择器

java - 应用程序无法启动 Activity 组件信息(Android)

java - Android M downloadprovider 下载失败 SecurityException

android - 水平滚动在 phonegap 中不起作用

android - 我如何停止android垃圾收集器?可能吗?

android - 移植到 BlackBerry Playbook 的 Android 应用程序有哪些有效的广告选项?

java - AsyncTask doInBackground 返回多个字符串