首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从资产读取文件

从资产读取文件
EN

Stack Overflow用户
提问于 2012-03-03 16:45:35
回答 14查看 376.4K关注 0票数 198
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()方法时,我无法识别。这里有什么解决方案吗?

EN

回答 14

Stack Overflow用户

发布于 2012-04-06 20:32:15

public String ReadFromfile(String fileName, Context context) {
    StringBuilder returnString = new StringBuilder();
    InputStream fIn = null;
    InputStreamReader isr = null;
    BufferedReader input = null;
    try {
        fIn = context.getResources().getAssets()
                .open(fileName, Context.MODE_WORLD_READABLE);
        isr = new InputStreamReader(fIn);
        input = new BufferedReader(isr);
        String line = "";
        while ((line = input.readLine()) != null) {
            returnString.append(line);
        }
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if (isr != null)
                isr.close();
            if (fIn != null)
                fIn.close();
            if (input != null)
                input.close();
        } catch (Exception e2) {
            e2.getMessage();
        }
    }
    return returnString.toString();
}
票数 40
EN

Stack Overflow用户

发布于 2019-04-17 14:18:25

kotlin的一行解决方案:

fun readFileText(fileName: String): String {
    return assets.open(fileName).bufferedReader().use { it.readText() }
}

您还可以将其用作扩展函数everyWhere

fun Context.readTextFromAsset(fileName : String) : String{
     return assets.open(fileName).bufferedReader().use { 
     it.readText()}
}

只需在任何上下文类中调用

context.readTextFromAsset("my file name")
票数 25
EN

Stack Overflow用户

发布于 2012-03-03 16:56:44

AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
    inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
    Log.e("message: ",e.getMessage());
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9544737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档