如何读取&QUOT文本文件;资产"目录作为一个字符串? [英] How to read a text file from "assets" directory as a string?

查看:137
本文介绍了如何读取&QUOT文本文件;资产"目录作为一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的资产文件夹中的文件......我怎么看它?

I have a file in my assets folder... how do I read it?

现在我想:

      public static String readFileAsString(String filePath)
        throws java.io.IOException{
            StringBuffer fileData = new StringBuffer(1000);
            BufferedReader reader = new BufferedReader(
                    new FileReader(filePath));
            char[] buf = new char[1024];
            int numRead=0;
            while((numRead=reader.read(buf)) != -1){
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
            reader.close();
            return fileData.toString();
        }

但它蒙上了空指针异常...

But it cast a null pointer exception...

文件名为原产地,它是在文件夹中的资产

the file is called "origin" and it is in folder assets

我试图用它转换:

readFileAsString("file:///android_asset/origin");

readFileAsString("asset/origin");``

但都失败了......什么建议?

but both failed... any advice?

推荐答案

您可以通过打开的输入流 AssetsManager

You can open an input stream using AssetsManager.

InputStream input = getAssets().open("origin");
Reader reader = new InputStreamReader(input, "UTF-8");

getAssets()上下文类的方法。

另外请注意,你不应该重新字符的缓冲区(<$ C C $> BUF =新的char [1024] ,你的周期的最后一行)。

Also note that you shouldn't recreate a buffer of characters (buf = new char[1024], the last line of your cycle).

这篇关于如何读取&QUOT文本文件;资产&QUOT;目录作为一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆