Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File path names for Windows and Linux

Tags:

java

Below is a path to my Windows directory. Normally the path should have \ instead of // but both seem to work.

String WinDir = "C://trash//blah//blah";

Same for a Linux path. The normal should have a / instead of //. The below and above snippet work fine and will grab the contents of the files specified.

String LinuxDir = "//foo//bar//blah"

So, both use strange declarations of file paths, but both seem to work fine. Elaboration please.

For example,

 File file = new File(WinDir);`
 file.mkdir();`
like image 553
Mason T. Avatar asked Jan 07 '14 19:01

Mason T.


1 Answers

Normally, when specifying file paths on Windows, you would use backslashes. However, in Java, and many other places outside the Windows world, backslashes are the escape character, so you have to double them up. In Java, Windows paths often look like this: String WinDir = "C:\\trash\\blah\\blah";. Forward slashes, on the other hand, do not need to be doubled up and work on both Windows and Unix. There is no harm in having double forward slashes. They do nothing to the path and just take up space (// is equivalent to /./). It looks like someone just did a relpace of all backslashes into forward slashes. You can remove them. In Java, there is a field called File.separator (a String) and File.separatorChar (a char), that provide you with the correct separator (/ or \), depending on your platform. It may be better to use that in some cases: String WinDir = "C:" + File.separator + "trash" + File.separator + "blah" + File.separator + "blah";

like image 93
Mad Physicist Avatar answered Oct 18 '22 00:10

Mad Physicist