首页 > 解决方案 > 从 MODE_PRIVATE FileNotFoundException 保存和读取文件

问题描述

我在资产文件夹中有一个 apk 文件。我想从 MODE_PRIVATE 复制 apk 文件然后读取它。我编写了写入和读取函数但无法读取我的文件。我有 FileNotFoundException 这是我的函数

 private void writeFilePrivate() {
    AssetManager assetManager = getAssets();
    InputStream in;
    FileOutputStream fos;
    try {
        in = assetManager.open("test.apk");
        fos = openFileOutput("tmp.apk", Context.MODE_PRIVATE);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            fos.write(buffer, 0, read);
        }
        in.close();
        fos.flush();
        fos.close();


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}



private File readFileFromPrivate() {
    int ch;
    StringBuffer fileContent = new StringBuffer("");
    FileInputStream fis;
    try {
        fis = openFileInput("test.apk");
        try {
            while ((ch = fis.read()) != -1)
                fileContent.append((char) ch);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    String data = new String(fileContent);
    File file = new File(data);
    return file;
}

我在日志中有这个错误

java.io.FileNotFoundException: /data/data/com.mypackage.music/files/test.apk: open failed: ENOENT (No such file or directory)

我究竟做错了什么 ?

标签: androidandroid-intentandroid-sdcardandroid-fileprovider

解决方案


推荐阅读