猿问

文件未找到时

出于某种原因(Java 新手),当我尝试从我的资源文件夹中读取 Excel 文件时,它显示它在那里,但是当我使用 FileInputStream 读取它时,我得到一个 FileNotFound 异常。有任何想法吗?


代码:


public static void openExcelSheet() throws IOException {

    FileInputStream fileInputStream = null;

    if(applicationSettings.class.getResourceAsStream("/files/Employees.xlsx") != null) {

        System.out.println("File Found");

        fileInputStream = new FileInputStream("/files/Employees.xlsx");

    }else {

        System.out.println("File Not Found");

    }


    XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);


    //int numberOfSheets = workbook.getNumberOfSheets();

    System.out.println(workbook.getAllNames());


    workbook.close();

}


白猪掌柜的
浏览 170回答 3
3回答

繁华开满天机

问题似乎是您的代码中的一些不正确假设:if (applicationSettings.class.getResourceAsStream("/files/Employees.xlsx") != null) {    System.out.println("File Found");    fileInputStream = new FileInputStream("/files/Employees.xlsx");} else {    System.out.println("File Not Found");}所以这是说:“如果我能"Employees.xlsx"在资源路径上找到,我就可以在具有相同路径的文件系统中找到它”。这里有两个错误的假设:您假设由于您"Employees.xlsx"在资源路径上发现将在文件系统中。这不是一个有效的假设:资源可以是(实际上,通常是)JAR 文件或类似文件的成员。资源或资源的容器可能已被即时下载到临时文件或内存中。资源可能是动态创建的;例如,通过一个聪明的类加载器解密或解压缩其他东西。您假设"Employees.xlsx"将具有与文件系统路径相同的资源路径。这几乎可以保证不是这种情况。(只有将文件系统的根目录放在类路径上才会出现这种情况......)我不知道你为什么要这样做。根据@fabian 的回答,POI 允许您从InputStream. 你不应该需要一个FileInputStream在这里。但是在资源路径上确实需要一个FileInputStream资源的情况下,可移植的解决方案是将资源复制到一个临时文件,然后FileInputStream在临时文件上打开一个。

慕桂英3389331

资源不一定是文件;它们可以作为条目存储在.jar档案中。即使它们作为文件存储在文件系统的目录结构中,工作目录也可能与当前工作目录不匹配。您应该直接使用InputStream返回的 bygetResourceAsStream而不是尝试打开一个新的:InputStream inputStream = applicationSettings.class.getResourceAsStream("/files/Employees.xlsx");if (inputStream != null) {    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);    //int numberOfSheets = workbook.getNumberOfSheets();    System.out.println(workbook.getAllNames());    workbook.close();} else {    System.out.println("Resource not found");}

呼啦一阵风

如果您的文件驻留在项目文件夹中,则问题是从名称前面删除斜杠fileInputStream = new FileInputStream("Employees.xlsx");那么应该工作。如果它在项目文件夹内的 files 文件夹内,则fileInputStream = new FileInputStream("files/Employees.xlsx");或者您可以提供文件的完整路径,这应该可以工作fileInputStream = new FileInputStream("/users/myfolder/files/Employees.xlsx");
随时随地看视频慕课网APP

相关分类

Java
我要回答