I am working on different platforms (Solaris/Windows). I need to create a File object which contains several path elements. The question is: is it better to create the final File object “step by step” or in a single call. The latter one assumes that Java does the right path mapping on different platforms. Does it always do a correct mapping due to different file separators?
File parent = // some directory;
// Use several file objects...
File myFile1 = new File(new File(new File(parent, "part1"), "part2"), "myfile");
// .. or use just on (on all platforms!)?
File myFile2 = new File(parent, "part1/part2/myfile");
The first solution is probably (a) slower and (b) less readable…
Use the 2nd one, and instead of hard-coding the forward slash, use
File.separatorChar/File.separator:Note that you don’t need to do this with Sun’s JVM – the
Win32FileSystemclass translates forward to backward slashes – if you look at its code, it hasslashandaltSlash, and in casealtSlash(/) is encountered, the class normalizes the pathBut, as pointed in the comments, in order to remain confident that your code will be portable, use the
File.separator