My application loads a txt file which is in PROJECTNAME/resource
folder.
Here is how I'm loading the file:
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();
}
NOTE: This works when I run from Eclipse, and doesn't when I Export to a Jar file (Extract required lib. into generated JAR). I know that the file is being extracted because its in the JAR file. Also the images work.
Error 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)
I also looked at the similar problem here, however they refer to file/URL outside JAR file.
A .jar entry is not a file; it is part of the .jar archive. It is not possible to convert a resource to Path. You’ll want to read it using getResourceAsStream
instead.
To read all of it, you have a few options. You can use a Scanner:
try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
bat = s.useDelimiter("\\Z").next();
if (s.ioException() != null) {
throw s.ioException();
}
}
You can copy the resource to a temporary file:
Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
Files.copy(stream, batFile);
}
You can simply read the text from an 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With