开发者

How do I create a File from a string that may represent an absolute or a relative path?

I have a directory pointed to by a File object called baseDir in which I keep most of my files.

I have a String f which may contain a relative filename, like "data.gz", or an absolute filename like "/mnt/data.gz" (its specified in a config file).

In the event that f is relative, it should be assumed that the file specified is within baseDir, but if it is absolute then it should be treated accordingly.

How do I create a File object that points to the file represent开发者_开发知识库ed by f?

I can think of hacky solutions to this (eg. if (f.startsWith("/")) ... but I'm hoping there is a "right way" to do this.

Oh, I tried using the File(File, String) constructor for the File object, but it doesn't do what I need it to do.


Use File.isAbsolute(x)

http://download.oracle.com/javase/6/docs/api/java/io/File.html#isAbsolute%28%29

If this returns false, prepend your basedir.


You can try the following:

File file = new File(f);
if(file.isAbsolute())
    ...

Be careful that the definition of absolute path is system dependent!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜