2016-07-04 57 views
2

我正在尝试使用Jexcel API创建Excel文件,并在我的手机上使用我的应用程序写入该文件。当我运行该应用程序时,它会抛出FileNotFoundException。我甚至尝试根据另一个这样的问题的答案创建一个文本文件,但它会抛出相同的错误。我已经在清单中给出了适当的权限,但我仍然无法找到问题所在。 请帮忙。尝试在Android中创建文件时出现FileNotFoundException

这里是我的代码

public WritableWorkbook createWorkbook(String fileName){ 

    //Saving file in external storage 
     File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 
     File directory = new File(sdCard.getAbsolutePath() + "/bills"); 

     //create directory if not exist 
     if(!directory.isDirectory()){ 
      directory.mkdirs(); 
     } 

     //file path 
     file= new File(directory, fileName); 
     if (file.exists()) 
      Log.e(taf,"file created"); 
     else 
     Log.e(taf,"file not created"); 

     WorkbookSettings wbSettings = new WorkbookSettings(); 
     wbSettings.setLocale(new Locale("en", "EN")); 
     wbSettings.setUseTemporaryFileDuringWrite(true); 
     WritableWorkbook workbook; 
     workbook=null; 

     try { 
      workbook = Workbook.createWorkbook(file, wbSettings); 
      Log.i(taf,"workbook created"); 
      //Excel sheet name. 0 represents first sheet 
      WritableSheet sheet = workbook.createSheet("MyShoppingList", 0); 

      try { 
       sheet.addCell(new Label(0, 0, "Subject")); // column and row 
       sheet.addCell(new Label(1, 0, "Description")); 


         String title = "blaj"; 
         String desc = "nxjdncj"; 

         int i = 1; 
         sheet.addCell(new Label(0, i, title)); 
         sheet.addCell(new Label(1, i, desc)); 
      } catch (WriteException e) { 
       e.printStackTrace(); 
      } 
      workbook.write(); 
      try { 
       workbook.close(); 
      } catch (WriteException e) { 
       e.printStackTrace(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    return workbook; 
} 

上执行,日志信息“未创建文件”打印。即时通讯新的android,所以请指出,即使是最基本的问题。

谢谢。

+0

你的Android版本是6.0吗? –

+0

是的。它适用于棉花糖前装置。我已经阅读了棉花糖设备,你必须添加运行时权限,但我不知道如何添加这些。 –

回答

3

实例化File不会创建该文件,只会为您提供一个File实例是否存在具有该特定路径和文件名的文件。

退房构造的源代码:

public File(String dirPath, String name) { 
    if (name == null) { 
     throw new NullPointerException("name == null"); 
    } 
    if (dirPath == null || dirPath.isEmpty()) { 
     this.path = fixSlashes(name); 
    } else if (name.isEmpty()) { 
     this.path = fixSlashes(dirPath); 
    } else { 
     this.path = fixSlashes(join(dirPath, name)); 
    } 
} 

实际创建你可以做这样的事情的文件:

if (!file.exists()) { 
    // file does not exist, create it 
    file.createNewFile(); 
} 
0

您需要在增加一个行:

file= new File(directory, fileName); 
file.createNewFile();// add this line 

我希望您已经在清单文件中添加了权限。

相关问题