从资产读取文件


177
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");    
     }
}

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

Answers:


225

这是我在一项活动中所做的活动,用于缓冲读取扩展/修改以符合您的需求

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
         }
    }
}

编辑:如果您的问题是在活动之外如何做,我的答案也许没用。如果您的问题仅是如何从资产读取文件,则答案在上方。

更新

要打开指定类型的文件,只需在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。我假设文件包含某种数据(即联系人列表),并且每一行都应分别处理。

万一您只想加载文件而不进行任何类型的处理,则必须mLine在每次通过时总结StringBuilder()并附加每个通过。

另一个编辑

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

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

语境

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

ContextInstance.getAssets();

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


2
@Stan,然后在评论中写出来,然后让作者决定是否要更新它。编辑是为了提高清晰度,而不是改变含义。代码修订版应始终先发布为注释。
KyleMit 2014年

2
您的代码不保证及时关闭流并释放资源。我建议您使用finally {reader.close();}
文森特·坎廷

2
我认为指出上述代码在ADT中显示错误-“ reader.close();”很有用。该行需要放在另一个try-catch块中。检查此线程:stackoverflow.com/questions/8981589/… :)
JakeP 2014年

1
getAssets是Context中的类,因此要在活动之外使用,需要对Context进行调用。因此,在活动之外,就像context.getAssets(.....)
Zoe

1
根据您的更新(感谢添加btw),在静态字段中包含上下文是内存泄漏。应谨慎使用并进行适当清理。否则最终会导致内存泄漏,这可能会对应用程序产生重大影响。
佐伊
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.