I need to implement portable code, but I do not know how to deal with different path conventions on different operating systems.
Asked
Active
Viewed 203 times
0
-
3have you already seen this Q/A: [http://stackoverflow.com/questions/3548775/platform-independent-paths-in-java][1] [1]: http://stackoverflow.com/questions/3548775/platform-independent-paths-in-java – Arruda Jun 15 '12 at 01:19
-
Ricardo, do you mean the code runs on both unix and windows, or that you need to have the program on one machine navigate the path on another machine? – Ryan Jun 15 '12 at 02:08
2 Answers
1
Ok. Using the File class, if you pass the a given path like so:
new File("myPathInUnixOrWindows");
You will get a system independent file path. Make sure you import:
import java.io.File;
if you just want the abstract base of the path pass it an empty string:
new File("");
http://docs.oracle.com/javase/6/docs/api/java/io/File.html
http://docs.oracle.com/javase/6/docs/api/java/io/File.html#File%28java.lang.String%29

Ryan
- 2,755
- 16
- 30
-
this is old documentation. Please provide good guidance and post at least the documentation to Java 6 or 7. – Luiggi Mendoza Jun 15 '12 at 01:20
-
This only helps when you are dealing with paths to files on this computer. I think the OP is asking about (for example) running an application on Windows that deals with UNIX pathnames. The `File` API doesn't help in that case. – Stephen C Jun 15 '12 at 01:21
-
Still doesn't help. How do I get `File` on a UNIX machine to generate pathname strings in Windows syntax? The problem is that the `File` API largely assumes that you are dealing with pathnames for >>this<< computer. – Stephen C Jun 15 '12 at 01:41
-
ok, but he is asking for portable code, why would i need to know for anything else than "this" machine? – Ryan Jun 15 '12 at 01:47
-
He asks *"How to treat the path of a file to the **different** operating systems in Java?"*. Now, we can't be sure, but >>I<< think this means manipulating file paths on one system that may have come from ... and need to go back to ... a different system. – Stephen C Jun 15 '12 at 02:04
-
not trying to troll you, (i'm going to ask the OP maybe he will respond), but what would be a good use case for that? I cant think of any, thats why im askin :) – Ryan Jun 15 '12 at 02:07
-1
new StringBuilder(dir)
.append(File.pathSeparatorChar)
.append(filename)
.toString()

sperumal
- 1,499
- 10
- 14