无法打开从原始文件夹复制的文件

时间:2013-11-14 08:55:00

标签: android excel

InputStream in = getResources().openRawResource(rawid);
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(FILE_DIRECTORY_PATH + "/" + fileName );
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    byte[] buff = new byte[1024];
    int read = 0;

    try {
        while ((read = in.read(buff)) > 0) {
            out.write(buff, 0, read);
        }

        out.flush();
        out.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
         try {
            in.close();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

在上面的代码的帮助下,我在sdcard上复制了一些.xls文件但是当我尝试使用以下代码打开文件时,它会出现错误,因为“此文档无法打开”或“文件格式不受支持”但它我去了文件浏览器并尝试打开文件,它会打开而不会出错。

Uri path = Uri.parse(FILE_DIRECTORY_PATH + "/abc.xls");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(path, "application/vnd.ms-excel");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    try {
        startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(BluTest.this, "No Application Available to View Excel", Toast.LENGTH_SHORT).show();
    }

1 个答案:

答案 0 :(得分:0)

InputStream in = getResources().getAssets().open(fileName);
    OutputStream out = null;
    try {
        out = new FileOutputStream(FILE_DIRECTORY_PATH + "/" + fileName );
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    byte[] buff = new byte[1024];
    int read = 0;

    try {
        while ((read = in.read(buff)) > 0) {
            out.write(buff, 0, read);
        }

        out.flush();
        out.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
         try {
            in.close();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

打开文件

    File temp = new File(GlobalValues.CSV_FILE_DIRECTORY_PATH
            + fileName);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://"+temp.getAbsolutePath() ), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    try {
        startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(this, "No Application Available to View Excel", Toast.LENGTH_SHORT).show();
    }

所以改变如下

  1. 我把文件放在资产文件夹中。
  2. 我们需要使用OutputStream而不是FileOutputStream。
  3. 获取文件路径的更改。