java - What is the best way to convert an absolute path name to be used as sub-path? -
i writing backup program using java , save files , directories backup destination based on absolute path names of sources.
the backup program supposed work under different operating systems (unix, windows, mac os x), need convert absolute pathnames of source files , directories.
so @ end convert absolute source path regular sub-path of destination. let me give examples.
unix
absolute source path: /home/thomas/data
destination path: /backup
effective destination: /backup/home/thomas/data
windows
absolute source path: c:\documents , settings\thomas
destination path: e:\backup
effective destination: e:\backup\c\documents , settings\thomas
i use string replacement operations expect run several trouble , start never ending correction story.
i think windows environment needs special handling because of leading drive letters. under *nix concatenate 2 paths. note source path unc-path under windows \\share\data.
i have searched around , found several similar questions none of them did answer mine (for example is there java utility convert string path use correct file separator char? or convert windows-style path unix path).
maybe has idea or hint me or knows library seeking for.
if you're using java 7 or later, paths
class , methods may of use. overview here: https://docs.oracle.com/javase/tutorial/essential/io/pathops.html
specifically use case, need subpath
(gets portion of path) , resolve
(combines 2 paths). try this:
path backuproot = paths.get("/backup"); path docroot = paths.get("/home/user1/docs"); // line gets full doc path without root path docs = docroot.subpath(0, docroot.getnamecount()); // line creates path "/backup/home/user1/docs" path backupdocs = backuproot.resolve(docs);
Comments
Post a Comment