使用Asset Manager打开文本文件并将其分配给InputStream

问题描述 投票:0回答:1

基本上我认为它可能是一个项目结构问题,因为我不确定文本文件的放置位置,我已经创建了一个目录资产,并在其中放置了一个名为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"); }
}

location of file

在此先感谢...本

java android inputstream android-assetmanager
1个回答
1
投票

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

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

screenshot

其次,在代码中更改此行

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

inputStream = assetManager.open("texts/myawesometext.txt");
© www.soinside.com 2019 - 2024. All rights reserved.