繁体   English   中英

在Android中从资源文件夹中读取文件时出现问题

[英]Trouble with reading file from assets folder in Android

这个问题与有关。 由于这是一个具体的问题,我在这里单独提出了这个问题。 我已经尝试创建一个文本文件“foo.txt”,将其读入我的Activity中:

File file = new File("/assets/foo.txt");
if ( file.exists() ){
    txtView.setText("Exists");
}
else{
    txtView.setText("Does not exist");
}

“foo.txt”文件位于我的资源文件夹中,我已经验证它存在于操作系统中。 我的TextView始终从上面的代码中获取文本“不存在”。 我试过去了

File file = new File("/assets/foo.txt");
Scanner in = new Scanner(file);

同样,但这会产生以下内联错误:“未处理的异常类型FileNotFoundException”。 Eclipse然后建议涉及try / catch,这会删除错误,但它也不能正常工作。

我也尝试将我的资源文件夹设置为“用作源文件夹”,但这没有任何区别。 我也尝试使用原始文件夹,因为有几个人建议没用。 我没有选择,真的需要帮助。 应该很容易......

另一种尝试是去

AssetManager assetManager = getResources().getAssets();
InputStream is = assetManager.open("assets/foo.txt");

但是这会在第二行产生内联错误:“未处理的异常类型IOException”。

在那种情况下,我与CommonsWare(这是安全方:)),但它应该是:

AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;

    try {
        inputStream = assetManager.open("foo.txt");
            if ( inputStream != null)
                Log.d(TAG, "It worked!");
        } catch (IOException e) {
            e.printStackTrace();
        }

不要使用InputStream is = assetManager.open("assets/foo.txt");

您不能使用File在运行时访问assets/ 您可以使用AssetManager在运行时访问assets/ ,您可以通过getResources().getAssets()

尝试这个 :

    private AssetManager am;
     am=getAssets();

     InputStream inputStream = null ;  
        try   
        {  
            inputStream = am.open("read.txt");  
        }   
        catch (IOException e) {}  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM