I’m reviewing my code
My Java application runs on Windows and Unix using Java 6 and manipulates files. I know I can use the file.separator to get the file separator in a filesystem independent way but if I ever use specify windows file separator char directly because is the ‘\’ which is also the Java escape character I can’t do manipulation of the file path. So in my code I’ve always stored the filepath in unix notation by replacing \’ with ‘/’ ,and these paths are stored in a database so I thought there was an escaping problem there as well. So I was under the illusion that trying to use file.separator would also fail because it would return ‘\’ rather than ‘\’ but now realise only need \ if I actually explicity specify it myself in quotes.
Now I’m thinking this is all unnecessary and as long as I always use file.separator I don’t need to do this conversion, am I right ?
EDIT:
Found a case where it seems to be a problem
"C:\Fred\test1.txt".split("\\\\");
"C:\Fred\test1.txt".split(System.getProperty("file.separator"));
if I want to split the string by \ I have double it up because \ has special meaning in a regular expression, so the line using file.separator fails with
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Pattern.java:1713)
at java.util.regex.Pattern.compile(Pattern.java:1466)
at java.util.regex.Pattern.<init>(Pattern.java:1133)
at java.util.regex.Pattern.compile(Pattern.java:823)
but on unix no such requirement the corresponding ‘/’ should not be escaped
EDIT 2:
This question has been asked before Splitting filenames using system file separator symbol the solution boils down to using Pattern.quote() around the input or trying to use file methods rather regular expressions. Both a little uneccessary I would prefer it if files could be viewed ins a system independent way, I not that Path in Java 7 has the same problem.
EDIT 3:
Also seeing a problem with reading/writing from db, created a separate question on that Storing Windows Path in Database and retrieving with Hibernate using java
Yes, you are right – if you use File.Seperator you dont need any additional escaping because in Windows it is already escaped for you. From the java documentation.