从原始文件夹复制的文件不能被打开

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

在上面的代码的帮助下,我复制了SD卡上的一些.xls文件,但是当我尝试使用下面的代码打开文件时,它给出的错误为“本文档无法打开”或“文件格式不支持”,但我去文件资源pipe理器并尝试打开它没有错误打开文件。

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

 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. 而不是FileOutputStream,我们需要使用OutputStream。
  3. 更改获取文件path。