maven - 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 ,但我仍然无法编译它。
解决方案
下面的代码适用于 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);
推荐阅读
- python - pandas:通过将 DataFrame 行与另一个 DataFrame 的列进行比较来创建新列
- vercel - Vercel 无服务器功能已超时错误
- django - 如何将存储库中的特定 django 文件夹部署到 azure 应用服务?
- ios - UITableView 自定义单元格高度不起作用
- angular - Angular 2 和 RxJS:Subject.next 在某些情况下不起作用
- sbt-native-packager - 在 maven repo 上找不到 native-package-manager 和 sbt-git 插件
- python - 使用 Selenium 访问日期元素
- nearprotocol - cargo check 无法构建 actix-cors
- sql - 从 SQL 代理作业运行时,部署的 SSIS 包失败
- excel - VBA Excel:使用 If 语句定义对象