1
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();
    }
4

1 回答 1

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. 获取文件路径的变化。
于 2013-11-19T15:59:43.357 回答