2016-07-04 60 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 

我希望您已經在清單文件中添加了權限。

相關問題