0

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

文件位置

在此先感谢...本

4

1 回答 1

1

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

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

截屏

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

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

inputStream = assetManager.open("texts/myawesometext.txt");
于 2019-03-03T02:29:18.580 回答