java - 输入流中的相对路径

标签 java inputstream

我有两个问题。

  1. 如何使用位于 res/ 目录中的文件 Export.xlsx 而是这个

    try (FileInputStream fileInputStream = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xlsx"))

  2. 从文件中读取数据,该文件位于 .jar 存档的同一目录中。

我尝试了什么?

第一。问:

String path = "res/"+sfilename+".xlsx";
System.out.println(getClass().getClassLoader().getResource(path).toString());
File file2 = new File(getClass().getClassLoader().getResource(path).toString());
try ( FileInputStream fileInputStream = new FileInputStream(file2))

file:/C:/Users/student/IdeaProjects/batch/out/production/batch/res/ExportBatch.xlsx
Work is finished!
java.io.FileNotFoundException: file:\C:\Users\student3\IdeaProjects\batch\out\production\batch\res\ExportBatch.xlsx (Синтаксическая ошибка в имени файла, имени папки или метке тома)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at workhere.WriterXlsx.<init>(WriterXlsx.java:20)
    at workhere.Start.start(Start.java:62)
    at workhere.Start.main(Start.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

enter image description here

最佳答案

你正在路上。

方法ClassLoader.getResource返回一个URL对象。您的 System.out.println 语句打印出此 URL。您可以看到 URL 协议(protocol)“file:”。

问题:File 构造函数不需要 URL,而只需要文件的路径。这就是 FileInputStream 找不到文件的原因。

解决方案:您不需要自己创建InputStream。只需使用 URL.openStream 即可。或者甚至更好:使用 ClassLoader.getResourceAsStream 向类加载器询问。

示例:

String path = "res/" + sfilename + ".xlsx";
URL resURL = getClass().getClassLoader().getResource(path);
try (InputStream inputStream = resURL.openStream()) {
    ...
}

或者:

String path = "res/" + sfilename + ".xlsx";
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path)) {
    ...
}

关于java - 输入流中的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18762862/

相关文章:

java - 如何访问嵌套在另一个泛型中的泛型?

java - 当从 java 调用 wget 并消耗 "error"和 "output"流时,子进程尝试多次运行不完整的命令

java - 如何将输入源转换为输入流,并将其作为参数提供给字符串读取器?

java - 使用 RestTemplate 获取 InputStream

java - InputStream.read(byte[] b) 返回意外的字节

java - 如何判断读取结束

java - 使用 Java 和 JXL/JExcel 读取电子表格

java - 我可以制作无边框的 JTable 列吗?

java - 尝试在工厂 org.apache.poi.xssf.usermodel.XSSFWorkbookFactory 和参数上调用 'createWorkbook' 时

java - 需要用 * 编码 String 中的重复模式,这样 * 意味着 "repeat from beginning"