Reputation: 23
I'm trying to recursively print all of the file paths from a directory
try {
Files.walkFileTree(Utils.getContentDirectory().toPath(), new SimpleFileVisitor<Path>() { //**Exception here**
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Utils.log(file.toString());
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
This is the directory I'm trying to read from, which does exist (I'm using maven and it's an internal directory)
public static File getContentDirectory() {
return new File(UltimateBugTracker.class.getClassLoader().getResource("resources/html/index.html").getFile()).getParentFile();
}
but for whatever reason it's throwing this exception
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 4: file:\C:\Users\raz\Desktop\WebServer.jar!\resources\html
which doesn't make sense because I'm using the build in fileInstance.toPath()
method to get the path. I don't understand why it is saying that it's an invalid path.
Upvotes: 0
Views: 81
Reputation: 15186
You are not passing a valid Path to walkFileTree, but a URI for a resource within a jar. Hopefully this example makes it clearer on how to walk the resources within your jar vs files in a directory:
public static void main(String[] args) throws IOException
{
var jar = Path.of("C:\\Users\\raz\\Desktop\\WebServer.jar");
System.out.println("isRegularFile()="+Files.isRegularFile(jar));
FileVisitor<? super Path> visitor = new FileVisitor<Path>()
{
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
{
System.out.println("dir START "+dir);
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
System.out.println("file "+file);
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
System.out.println("file fail "+file);
return FileVisitResult.CONTINUE;
}
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
{
System.out.println("dir END "+dir);
return FileVisitResult.CONTINUE;
}
};
try (FileSystem fs = FileSystems.newFileSystem(jar))
{
Path path = fs.getPath("/resources/html");
System.out.println("walkFileTree within archive "+ jar+" starting at path: "+path);
Files.walkFileTree(path, visitor);
}
Path parent = jar.getParent();
System.out.println("walkFileTree at "+ parent);
Files.walkFileTree(parent, visitor);
}
Upvotes: 1