0

I am creating a zip file from the contents of a source directory using NIO2. I am using a ZipFileSystem, for which I first have to gain an instance, and then generate paths. The generated paths can then be used to create entries in the zip file using Files.createDirectory(pathInZip) or Files.copy(sourcePath, destPathInZip). This works fine, but there is a moment of uglyness that I would like to avoid:

 // within the SimpleFileVisitor that walks through sourceDirFile
 @Override
 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    Path pathInZip = zipFileSystem.getPath(sourceDirPath.relativize(file).toString()); // <-- ?!
    Files.copy(file, pathInZip);
    return FileVisitResult.CONTINUE;
 }

Is there a way to copy a Path from one FileSystemProvider into a Path from another without relying on aPath.toString()?. It seems ugly. I could always iterate over one path, incrementally building the other... but it would seem so easy to have a FileSystem.getPath(Path anotherPath) that I took the time to write this post.

tucuxi
  • 17,561
  • 2
  • 43
  • 74

2 Answers2

1

i have been using below dirutils lib that i think does what u are trying to do. it uses toPath.resolve()

https://github.com/bbejeck/Java-7/blob/master/src/main/java/bbejeck/nio/files/visitor/CopyDirVisitor.java

Edit: lol now that you say it I revisited my code and noticed I had patched just that part of the lib. One forgets things so easily..

 @Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

    Path relativizedPath =fromPath.relativize(dir);

    Path targetPath = toPath.resolve(relativizedPath.toString());
    if(!Files.exists(targetPath)){
        Files.createDirectory(targetPath);
    }
    return FileVisitResult.CONTINUE;
}
Aksel Willgert
  • 11,367
  • 5
  • 53
  • 74
  • 2
    Nice code - but it does not work cross-filesystem. It seems that paths are linked to the filesystems they originate from... – tucuxi Oct 08 '12 at 18:56
1

I have written some utility methods for this. Maybe you find them useful (the library is Open Source).

Tutorial: http://softsmithy.sourceforge.net/lib/current/docs/tutorial/nio-file/index.html

Javadoc: http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-core/index.html

Maven:

<dependency>  
    <groupId>org.softsmithy.lib</groupId>  
    <artifactId>softsmithy-lib-core</artifactId>  
    <version>0.2</version>   
</dependency> 

More info: http://puces-blog.blogspot.ch/2012/07/news-from-software-smithy-version-02.html

Puce
  • 37,247
  • 13
  • 80
  • 152