开发者

Java library function to find shadow file in different directory

开发者 https://www.devze.com 2023-01-16 17:18 出处:网络
I often have code where I loop over a directory (including 开发者_如何学Csubdirectories) and need to move / copy the file to a different directory. What I find tedious is the process of identifying wh

I often have code where I loop over a directory (including 开发者_如何学Csubdirectories) 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)


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).


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.


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:

  • FileUtils.moveFileToDirectory()
  • FileUtils.copyDirectory()
  • FileUtils.moveDirectory()

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

  • FileUtils.copyDirectory(File, File, FileFilter)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号