【问题标题】:Opening a textFile with the AssetManager and assigning it to a InputStream使用 Asset Manager 打开文本文件并将其分配给 InputStream
【发布时间】:2019-07-24 10:48:29
【问题描述】:

基本上我认为这可能是一个项目结构问题,因为我不确定将文本文件放在哪里,我创建了一个目录资产并在其中放置了一个名为 texts 的文件夹,其中放置了 myawesometext.txt。

我得到的错误是调用它找不到文件的异常。

我认为这可能与权限有关,但找不到与其相关的权限,因为它不是外部存储。

我的问题是,如果我有文件并且我正在运行应用程序,我应该在哪里创建要读取的结构中的资产文件夹我已经仔细检查了拼写(没有拼写错误)它只是捕获了我的异常。

类:

public class AssetsTest extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView textView = new TextView(this);
    setContentView(textView);
    AssetManager assetManager = getAssets();
    InputStream inputStream = null;
    try {
        inputStream = assetManager.open("texts/myawesometext");
        String text = loadTextFile(inputStream);
        textView.setText(text);
    } catch (IOException e) { textView.setText("Couldn't load file");
    } finally {
        if (inputStream != null)
            try { inputStream.close();
            } catch (IOException e) { textView.setText("Couldn't close file");
            } }
}
    public String loadTextFile(InputStream inputStream) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] bytes = new byte[4096];
        int len = 0;
        while ((len = inputStream.read(bytes)) > 0) byteStream.write(bytes, 0, len);
        return new String(byteStream.toByteArray(), "UTF8"); }
}

在此先感谢... 本

【问题讨论】:

    标签: java android inputstream android-assetmanager


    【解决方案1】:

    您的资产文件夹位置不正确,您的代码也不正确。请按照以下步骤操作。

    首先,将当前的assets文件夹移动到src/main

    其次,将代码中的这一行从

    inputStream = assetManager.open("texts/myawesometext");
    

    inputStream = assetManager.open("texts/myawesometext.txt");
    

    【讨论】:

    • 天才非常感谢汤米,你是最棒的!!回头看的简单错误只是看不到它。我尝试了各种不同的文件目录名称,但问题是它不在 src main 中。再次感谢
    • @beni 很高兴听到这个消息。快乐编码:)
    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多