I am trying to get .cer files packed inside a jar and install them dynamically to keystore using java .
private List<File> doSomething(Path p) {
List<java.io.File>FileList=new ArrayList<>();
try {
int level = 1;
if (p.toString().equals("BOOT-INF/classes/certs")) {
level = 2;
Stream<Path> walk = Files.walk(p, level);
for (Iterator<Path> it = walk.iterator(); it.hasNext(); ) {
System.out.println(it.next());//getting all .cer files in the folder
FileList.add(it.next().toFile());//getting an error UnsupportedOperationException Path not associated with
}
logger.info("fileList" + FileList.size());
}
}
catch(Exception e)
{
logger.error("error-----------"+e);
}
return FileList;
}
I am getting UnsupportedOperationExceptionin toFile(), believe this is because I am trying to access file inside a jar. Is there any way to conver this Path(nio.file.Path) to actual file or stream?
Path#toString() won't return the path with forward slashes (/) like the string path you are comparing to. It returns it with back-slashes (\) so your comparison won't ever become true.
When reading paths from the local file System always use the path or file separator related to the System. To do this you can use the String#replaceAll() method to convert any path name slashes to what is appropriate for the file system your code is operating on, for example:
This should work fine:
If you want to base your listing on specific file extensions and or the contents of a JAR file then you will need to do something a little different. The code below is very similar to the code you have been using with the exception that:
List<String>
instead ofList<File>
;onlyExtensions
) has been added to the method so that one (or more) file name extensions can be applied to return a list that contains only paths where the file names contain the extension(s) applied. If an extension supplied happens to be".jar"
then the contents of that JAR file will also be applied to the returned List. If nothing is supplied then all files are returned in the list.For JAR files a helper method is also provided:
Modify any of this code as you see fit:
The JAR file helper method:
To use the getFileList() method you might do something like this: