Can I compose two file paths without needing their toString() methods?
Imagine I have a 'base' path object, denoting a directory, and a 'relative' path object denoting some file within the base.
I would expect that code to look somewhat like
AbsolutePath base = new AbsolutePath("/tmp/adirectory");
RelativePath relativeFil开发者_如何转开发ePath = new RelativePath("filex.txt");
AbsolutePath absoluteFile = base.append( relativeFilePath );
But in the Java API (which I don't yet know very well) I find only File
, with which I can do nothing better than
File base = new File("/tmp/adirectory");
File relativeFilePath = new File("filex.txt");
File absoluteFile = base.toString()
+ File.separator
+ relativeFilePath.toString();
Is there a better way?
The closest you can get with java.io.File
is the File(File, String)
constructor:
File base = ...;
File relative = ...;
File combined = new File(base, relative.toString());
If you can use the Path
class introduced in Java 7, then you can use the resolve()
method, which does exactly what you want:
Path base = ...;
Path relative = ...;
Path combined = base.resolve(relative);
Please note that if base
is not an absolute path, then combined
won't be absolute either! If you need an absolute path, then for a File
you'd use getAbsoluteFile()
and for a Path
you'd use toAbsoutePath()
.
Yes. new File(base, "filex.txt")
will create a file names "filex.txt" in the directory base.
There is no need to create a relativeFilePath
File instance with just the relative name if what you want to do is make it relative to another directory than the current one.
how about:
File base = new File("/tmp/adirectory");
File absoluteFile = new File(base, "filex.txt");
EDIT: Too late @JB Nizet pipped me at the post...
The File class has some constructors which may be of interest to you:
File base = new File("/tmp/adirectory");
File absolute = new File(base, "filex.txt");
File absolute2 = new File("/tmp/adirectory", "filex.txt");
精彩评论