Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java File Path Best Practice

Tags:

java

If operating system is Windows, which one given below is a best approach of coding 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(); 
like image 659
Saravana Kumar Avatar asked Aug 06 '26 17:08

Saravana Kumar


2 Answers

EDIT: Given the comments, I should clarify. This definitely depends on context. What are you trying to do? If you're trying to create a file path in the "native" operating system format, I would use option 5, using File:

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

Or better, put this logic into a 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 call it with:

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

(It's possible that this exists somewhere in recent JREs, but if so I don't know where.)

If you only need something that will work for FileInputStream etc, then I might just hard-code the forward-slashes, for two reasons:

  • They're easier to read than the backslashes
  • They'll work on other operating systems too

Either way, I would probably still create a File, as it gives clearer meaning to the value. Most IO APIs in Java accept a File where appropriate - and it makes it obvious to all the code surrounding it that this is a file path. So you could use:

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

... and that would still work on Windows. You could then use File.getCanonicalFile to get a canonical representation, which would have backslashes rather than forward slashes, if you wanted.

like image 144
Jon Skeet Avatar answered Aug 08 '26 20:08

Jon Skeet


Jon Skeet is right but I want to say that Microsoft impose the use of \ only in command interpreter. Every where in the API you can use /.

So you can use String f = "some/path/file.ext"; everywhere but in ProcessBuilder if the launched program is cmd.exe.

To convert paths, I use String.replaceAll( "\\\\", "/" );

like image 42
Aubin Avatar answered Aug 08 '26 22:08

Aubin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!