我已尝试过每条路径,但无法找到文件路径。
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语句都会运行
“找不到档案”
么?
答案 0 :(得分:0)
执行File file = new File("/resources/Shop-Order.xlsx")
时,JVM会在本地文件系统中查找该文件。由于您已将excel文件放在资源(部署在jar中)中,因此需要从类路径中获取它。
试试这个:
File file = new File(JobOrderGenerator.class.getResource("Shop-Order.xlsx").toURI());
另外,就像评论中提到的@dhh一样 - 文件名中有一个空格。
答案 1 :(得分: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());