簡體   English   中英

在 Java 程序中找不到資源文件

[英]Resource file not found in Java program

我已經嘗試了所有可能的路徑,但無法找到文件路徑。

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

文件在資源文件夾中

每當我運行程序時,else 語句都會運行說

“未找到文件”

建議?

您無法直接獲取指向其路徑的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());

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

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

另外,就像評論中提到的@dhh - 文件名中有一個空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM