tags:

views:

76

answers:

2

I often have code where I loop over a directory (including subdirectories) and need to move / copy the file to a different directory. What I find tedious is the process of identifying where the file will go. I have often done that, usually like this:

File shadow = new File(sourceFile.getAbsolutePath()
                        .replace(
                             sourceFolder.getAbsolutePath(),
                             targetFolder.getAbsolutePath()
                        )
              );

My question: is there a standard routine to do this or something similar in any major open source library? I didn't find one in Commons IO anyway...

I am not looking for complete move / copy solutions, I know tons of those. I just want the equivalent of the above code.


An Example, as requested:

Source folder:

src/main/resources

Target folder:

target/classes

Source file:

src/main/resources/com/mycompany/SomeFile.txt

Target file (the one I'm looking for):

target/classes/com/mycompany/SomeFile.txt

(I usually do stuff like this in a maven context, hence these folders but they could be non-maven folders, as well, the question has nothing to do with maven)

+1  A: 

Have you seen the org.apache.commons.io.FilenameUtils concat method? It takes a base directory (your target) and file-name to append. You would need to calculate the sourceFolder prefix ("src/main/resources".length()) and do a substring. Something like:

File shadow = new File(FilenameUtils.concat(targetFolder.getAbsolutePath(),
    sourceFile.getAbsolutePath().substring(prefixLength));

Not much better than rolling you own though.


For posterity, Apache's org.apache.commons.io.FileUtils also has functionality that you might use although I don't see a specific solution to your question:

You could use copyDirectory with a FileFilter to choose which files to move over:

Gray
That's not an answer to my question. I know all these methods. I just want the method that does what the code I wrote does.
seanizer
Figured that you did. How about using copyDirectory with a FileFilter? That should track the src and destination paths for you.
Gray
As I said, I am not looking for a copy solution, but for a generic mechanism to identify a file's sibling in another directory (this has many applications, only one of them being to copy the file).
seanizer
BTW, I took the liberty to edit the format of your post.
seanizer
The concat method is nice, thanks (+1)
seanizer
+1  A: 

What you are looking for I have never found either but it will exist soon when JDK 7 (eventually) crawls out the door.

Path.relativize(Path) (Java 7 API)

For now I would stick to your current solution (or roll your own equivalent of the above).

Mike Q
This is great, I'll definitely use this a lot, thanks (+1). Yes of course, I know my code works, but it's boilerplate that I have written for x projects and I hate not having a shortcut for code like that.
seanizer