Java 7 provide directory tree traversal trough Files.walkFileTree Method which basically traverse the hierarchical folder structure
Path Objects
Path object represent the sequence of Directory structure to find the file resource
How to construct path object
Paths.get(“/BaseDir”); // return path string “/BaseDir” Paths.get(“/BaseDir”,”SubDir”); // return the path string “/BaseDir/SubDir”path object can be manipulated using the Path.resolve and Path.relativize,lets have a look
Path base = Paths.get(“/BaseDir”); //this is the base path Path filePath = base.resolve(“SubDir/somefile.txt”); // the filePath is “/BaseDir/SubDir/somefile.txt” while the base path remains “/BaseDir”The very useful method of the Path class is Path.getFileName which inturn return the farthest element which is eighter a file or directory,lets have an example
suppose we have created the filePath as “/BaseDir/SubDir/somefile.txt” filePath.getFileName() // returns the name of the file as somefile.txt suppose we have created the dirPath as “/BaseDir/SubDir/SomeDir” dirPath.getFileName() // return the directory name as SomeDir
How to copy a file
Path srcPath = …...... Path targetPath = …............... Path basePath = …...... Files.copy(srcPath,targetPath.resolve(basePath.relativize(srcPath)));
No comments:
Post a Comment