简体   繁体   English

我可以在不需要其toString()方法的情况下编写两个文件路径吗?

[英]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 relativeFilePath = 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 但是在Java API(我还不太了解)中,我只找到了File ,我无法做到这一点

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 : java.io.File最接近的是File(File, String)构造函数

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: 如果您可以使用Java 7中引入的Path类,那么您可以使用resolve()方法 ,它完全符合您的要求:

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! 请注意,如果base不是绝对路径,那么combined也不是绝对的! If you need an absolute path, then for a File you'd use getAbsoluteFile() and for a Path you'd use toAbsoutePath() . 如果您需要绝对路径,那么对于File您将使用getAbsoluteFile()而对于您将使用toAbsoutePath()Path

Yes. 是。 new File(base, "filex.txt") will create a file names "filex.txt" in the directory base. new File(base, "filex.txt")将在目录库中创建文件名“filex.txt”。

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. 如果您要执行的操作是使其相对于当前目录而不是另一个目录,则无需仅使用相对名称创建relativeFilePath文件实例。

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... 编辑:太晚了@JB Nizet在帖子里揍了我一下......

The File class has some constructors which may be of interest to you: File类有一些您可能感兴趣的构造函数:

File base = new File("/tmp/adirectory");
File absolute = new File(base, "filex.txt");
File absolute2 = new File("/tmp/adirectory", "filex.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM