Java File Path Best Practice -


if operating system windows, 1 given below 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(); 

edit: given comments, should clarify. depends on context. trying do? if you're trying create file path in "native" operating system format, use option 5, using file:

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

or better, put logic method:

public static file newfile(string root, string... parts) {     // todo: check nothing's null (root, parts, each element of parts)     file ret = new file(root);     (string part : parts) {         ret = new file(ret, part);     }     return ret; } 

then can call with:

file f = someutilityclass.newfile("some", "path", "file.ext"); 

(it's possible exists somewhere in recent jres, if don't know where.)

if need work fileinputstream etc, might hard-code forward-slashes, 2 reasons:

  • they're easier read backslashes
  • they'll work on other operating systems too

either way, still create file, gives clearer meaning value. io apis in java accept file appropriate - , makes obvious code surrounding is file path. use:

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

... , still work on windows. use file.getcanonicalfile canonical representation, have backslashes rather forward slashes, if wanted.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -