Java file path best practices

If the operating system is windows, which of the following is the best way to write in Java?

1)

String f = "some\\path\\file.ext";

2)

String f = "some/path/file.ext";

3)

String f = "some"+File.separator+"path"+File.separator+"file.ext";

4)

String f = new StringBuilder("some").append(File.separator).append("path").append(File.separator).append("file.ext").toString();

Solution

Editor: in view of the comments, I should clarify It absolutely depends on the background What would you do? If you try to create a file path in the "native" operating system format, I will use option 5, file:

File f = new File("some");
f = new File(f,"path");
f = new File(f,"file.ext");

Or better, put this logic into the method:

public static File newFile(String root,String... parts) {
    // TODO: Check that nothing's null (root,parts,each element of parts)
    File ret = new File(root);
    for (String part : parts) {
        ret = new File(ret,part);
    }
    return ret;
}

Then you can use:

File f = SomeUtilityClass.newFile("some","path","file.ext");

(this may exist in the recent JRE, but if so, I don't know where it is.)

If you only need something suitable for FileInputStream, etc., I may just hard code the forward slash for two reasons:

>They are easier to read than backslashes > they will also work on other operating systems

Either way, I may still create a file because it gives clearer values Most IO APIs in Java accept files in place - and it makes all the surrounding code obvious that this is a file path So you can use:

File file = new FIle("some/path/file.ext");

... this still applies to windows You can then use file Getcanonicalfile to get the specification. If you like, you can use backslash instead of forward slash

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>