将文件从资产文件夹复制到本地目录并打开文件android nougat

时间:2017-05-11 06:06:04

标签: android android-7.0-nougat

将文件从资产文件夹复制到本地目录并打开文件android nougat没有打开。

以下是复制文件然后打开文件的代码。

public void openSample(Context context) {
        try {
            copyFile(context.getAssets().open("sample.xlsx"), new FileOutputStream(new File(Environment.getExternalStorageDirectory() , "Download/sample.xlsx")));
            File excelFile = new File(Environment.getExternalStorageDirectory() , "Download/sample.xlsx");
            Uri path = null;
            Intent intent = null;
            intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                path = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", excelFile);

                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                path = Uri.fromFile(excelFile);
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setDataAndType(path, "application/vnd.ms-excel");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        if (out != null) {
            out.close();
        }
    }

找到下面的附件,查看打开文件时出现的错误。

Excel_Screenshot

提前致谢。

1 个答案:

答案 0 :(得分:0)

public void openSample(Context context){
        in=assetManager.open(fileName);
        outFile=new File(getExternalFilesDir(null),fileName);
        out=new FileOutputStream(outFile);

        copyFile(in,out);
        in.close();
        in=null;
        out.flush();
        out.close();
        out=null;

        }catch(Exception e)
        {
        Log.e("tag",e.getMessage());
        }
        Intent intent=new Intent(Intent.ACTION_VIEW);
        Uri contentUri=getUriForFile((context, context.getApplicationContext().getPackageName() + ".provider", outFile);
        intent.setDataAndType(
        contentUri,
        "application/vnd.ms-excel");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
        }

private void copyFile(InputStream in,OutputStream out)throws IOException
        {
        byte[]buffer=new byte[1024];
        int read;
        while((read=in.read(buffer))!=-1)
        {
        out.write(buffer,0,read);
        }
        }