我的应用程序加载文件PROJECTNAME/resource夹中的txt文件。
这是我加载文件的方式:
URL url = getClass().getClassLoader().getResource("batTemplate.txt");
java.nio.file.Path resPath;
String bat = "";
try {
resPath = java.nio.file.Paths.get(url.toURI());
bat = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
} catch (URISyntaxException | IOException e1) {
e1.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
注意:这在我从Eclipse运行时有效,而在我导出到Jar文件(将所需的库提取到生成的JAR中)时不起作用。我知道该文件正在提取中,因为它在JAR文件中。图像也起作用。
错误MSG:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
Illegal character in path at index 38: file:/C:/DataTransformation/Reports Program/ReportsSetup.jar
at com.sun.nio.zipfs.ZipFileSystemProvider.uriToPath(ZipFileSystemProvider.java:87)
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:166)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
at java.nio.file.Paths.get(Unknown Source)
at ReportSetup$13.mouseReleased(ReportSetup.java:794)
Run Code Online (Sandbox Code Playgroud)
我在这里也看到了类似的问题,但是它们引用的是JAR文件之外的文件/ URL。
.jar 条目不是文件;它是 .jar 档案的一部分。无法将资源转换为路径。你会想使用它来阅读它getResourceAsStream。
要阅读所有内容,您有几个选择。您可以使用扫描仪:
try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
bat = s.useDelimiter("\\Z").next();
if (s.ioException() != null) {
throw s.ioException();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将资源复制到临时文件:
Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
Files.copy(stream, batFile);
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地从 InputStreamReader 读取文本:
StringBuilder text = new StringBuilder();
try (Reader reader = new BufferedReader(
new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("batTemplate.txt"),
StandardCharsets.UTF_8))) {
int c;
while ((c = reader.read()) >= 0) {
text.append(c);
}
}
String bat = text.toString();
Run Code Online (Sandbox Code Playgroud)