首页 > 解决方案 > Java I/O 帮助。Jar 无法打开文件:URI 不是分层的

问题描述

我已经搜索了 3 天,现在不停地查看我能找到的每个帖子。我的程序在 IntelliJ 上运行,但无法在可执行文件上运行。您的帮助将不胜感激:)

更重要的是,我在哪里可以找到深入的用户友好教程?有我可以支付的课程或书籍吗?在 Udemy 上,java 类完全没有提到类路径和 URI 等 I/O。TutorialsPoint 简要介绍了 I/O,但并不深入。我错过了什么?有没有更简单的方法来做这一切?

对我不起作用的类似帖子: Java Jar 文件:使用资源错误:URI 不是分层的 https://stackoverflow.com/a/27149287/155167

我正在尝试加载一个 excel 文件。我正在使用 Maven。Apache POI 说它需要一个文件。所以InputStream 不起作用http://poi.apache.org/components/spreadsheet/quick-guide.html#FileInputStream

当我使用 java -jar jarFile 时,它​​给了我错误

C:\Users\1010\Documents\Personal\MonsterManager>java -jar monsterManagerVer3.jar

Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical

        at java.base/java.io.File.<init>(File.java:421)
        at LoadExcel.<init>(LoadExcel.java:62)
        at monsterRunner.<init>(monsterRunner.java:13)
        at monsterRunner.main(monsterRunner.java:24)

这是代码

public LoadExcel() throws IOException, URISyntaxException, InvalidFormatException {
        mNames = null;
        URL ins = this.getClass().getResource("/excel_List.xlsx");
        if (ins == null)
            throw new FileNotFoundException("The XLSX file didn't exist on the classpath");
        ins.toString().replace(" ","%20"); //<-Runs without this part

        File file = new File(ins.toURI()); //this is line 62


       // File f = new File(getClass().getResource("/MyResource").toExternalForm());
        //String path = this.getClass().getClassLoader().getResource("/excel_List.xlsx").toExternalForm();
        //File file = new File(path);
        OPCPackage pkg = OPCPackage.open(file);
        XSSFWorkbook wb = new XSSFWorkbook(pkg);
        //FileInputStream fis=new FileInputStream(new File(excelFile));
       // XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheetAt(0);
        loadExcel(sheet);
        cacheNames();
      //  fis.close();
        wb.close();
    }

如果有帮助,这里是 excel 文件的路径:src\main\resources\excel_List.xlsx

更新:所以我从资源文件夹 \nameOfMyProgram\excel_List.xlsx 中取出了 excel 文件,现在我收到了这个错误。我尝试了使用类加载器、类和线程的几个版本来解决这个错误,从不同的方式将文件加载为 InputStream ,但我仍然无法编译它。

错误和我的代码

标签: mavenioapache-poiuriexecutable-jar

解决方案


下面的代码适用于 jar 可执行文件

String path = new File("excel_List.xlsx").getAbsoluteFile().toString();
            File file = new File(path);
            if(!file.exists()){
                JOptionPane.showMessageDialog(null,"File not found!");
                System.exit(0);
            }
            OPCPackage pkg = OPCPackage.open(file);
            XSSFWorkbook wb = new XSSFWorkbook(pkg);

推荐阅读