【问题标题】:FileNotFoundException while reading a xlsx file读取 xlsx 文件时出现 FileNotFoundException
【发布时间】:2015-08-20 01:03:33
【问题描述】:

我正在尝试使用以下代码从项目文件夹中读取 .xlsx 文件,但它总是抛出 FileNotFoundException。我已经附上了文件所在的项目结构。

public static void main(String[] args)  {
    try {
        String excelFilePath = "‪DataModel.xlsx";
        File file = new File(excelFilePath);
        FileInputStream fis = new FileInputStream(file);         

    } catch (Exception ex) {
        System.out.print(ex);
    }
}

【问题讨论】:

  • 您应该使用 DataModel.xlsx 而不是 DataModel.txt
  • 事实上我只使用了 xlsx。现在修改了

标签: java filereader filenotfoundexception fileinputstream


【解决方案1】:

这是我通常的处理方式:

File file = new File( javaApplication2.class.getResource( excelFilePath ).getPath() );

【讨论】:

  • 我使用 classLoader.getResource() 解决了这个问题。我同意你的 voipdaddy,这是一个更好的方法
  • 请记住,getResource 只能读取类路径中的文件。因此,当您的程序在生产中时,Excel-File 必须在类路径中(在 jar 中或通过 java 的 -cp 参数添加)!
【解决方案2】:

classLoader.getResource() 解决了问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多