2015-06-16 74 views
-2

我試過了每一條可以找到的路徑,但無法找到文件路徑。在Java程序中找不到資源文件

public class JobOrderGenerator { 

    private File file = new File("/resources/Shop-Order.xlsx"); 
    private int sheetNumber = 0; 

    public JobOrderGenerator(List<ShopOrder> shopOrder) throws InvalidFormatException, IOException { 

     for (ShopOrder shopOrder1 : shopOrder) { 

      writeToSpecificCell(2, 1, sheetNumber, shopOrder1.getPo_number()); //Po Number 
      writeToSpecificCell(7, 3, sheetNumber, shopOrder1.getPo_number()); //Part Number 
      LocalDate date = shopOrder1.getPo_due_date(); 
      String dateToString = date.toString(); 
      writeToSpecificCell(1, 2, sheetNumber, dateToString); //Due_Date 
      writeToSpecificCell(7, 5, sheetNumber, Integer.toString(shopOrder1.getPart_quantity())); //Quantity 
      //writeToSpecificCell(1,2,sheetNumber, shopOrder.get); //Material 
      writeToSpecificCell(8, 3, sheetNumber, shopOrder1.getPart_decription()); //Part Description 
      //writeToSpecificCell(1,2,sheetNumber, shopOrder.getCustomer()); //Customer 
      writeToSpecificCell(10, 1, sheetNumber, shopOrder1.getMachine_number()); //Machine 

      sheetNumber++; 

     } 
    } 

    void writeToSpecificCell(int rowNumber, int cellNumber, int sheetNumber, String value) throws InvalidFormatException, IOException { 

     if(file.exists()){ 
      System.out.println("Was was found"); 
     } else { 
      System.out.println("File was NOT found"); 
     } 

File is in the resources folder

每當我運行else語句運行的程序說

「文件未找到」

建議嗎?

+0

你是如何得到文件的? – Arpit

+0

@Arpit我點擊intellji中的文件,找到它的路徑,並在每次失敗時取出一個/符號或單詞,但它仍然沒有找到它。 – Drew1208

+0

你能顯示代碼嗎? – Arpit

回答

0

你不能直接引用它的File它的路徑。相反,你應該使用Classloader

ClassLoader classLoader = getClass().getClassLoader(); 
File file = new File(classLoader.getResource("Shop-Order.xlsx").getFile()); 

如果你想加載File靜態方式,你必須調整代碼點點getClass()方法的非靜態方法不能從靜態方法或塊調用。

ClassLoader classLoader = JobOrderGenerator.class.getClassLoader(); 
File file = new File(classLoader.getResource("Shop-Order.xlsx").getFile()); 
0

當您執行File file = new File("/resources/Shop-Order.xlsx")時,JVM將在本地文件系統中查找該文件。既然你已經將excel文件放在資源中(這是部署在jar中),你需要從類路徑中獲取它。 試試這個:

File file = new File(JobOrderGenerator.class.getResource("Shop-Order.xlsx").toURI()); 

此外,像在評論中提到@dhh - 你必須在文件名中一個空格。

相關問題