I have developed a number of classes which manipulate files in Java. I am working on a Linux box, and have been blissfully typing new File(\"path/to/some/file\");
I create this function to check if a String contain a \
character then convert them to /
public static String toUrlPath(String path) {
return path.indexOf('\\') < 0 ? path : path.replace('\\', '/');
}
public static String toUrlPath(Path path) {
return toUrlPath(path.toString());
}
String fileName = Paths.get(fileName).toString();
Works perfectly with Windows at least even with mixed paths, for example
c:\users\username/myproject\myfiles/myfolder
becomes
c:\users\username\myproject\myfiles\myfolder
Sorry haven't check what Linux would make of the above but there again Linux file structure is different so you wouldn't search for such a directory
For anyone trying to do this 7 years later, the apache commons separatorsToSystem method has been moved to the FilenameUtils class:
FilenameUtils.separatorsToSystem(String path)
Apache Commons
comes to the rescue (again). The Commons IO
method FilenameUtils.separatorsToSystem(String path) will do what you want.
Needless to say, Apache Commons IO
will do a lot more besides and is worth looking at.
This is what Apache commons-io does, unrolled into a couple of lines of code:
String separatorsToSystem(String res) {
if (res==null) return null;
if (File.separatorChar=='\\') {
// From Windows to Linux/Mac
return res.replace('/', File.separatorChar);
} else {
// From Linux/Mac to Windows
return res.replace('\\', File.separatorChar);
}
}
So if you want to avoid the extra dependency, just use that.
I think there is this hole in Java Paths.
String rootStorePath = Paths.get("c:/projects/mystuff/").toString();
works if you are running it on a system that has the file system you need to use. As pointed out, it used the current OS file system.
I need to work with paths between windows and linux, say to copy a file from one to another. While using "/" every works I guess if you are using all Java commands, but I need to make an sftp call so using / or file.separator
etc... does not help me. I cannot use Path()
because it converts mine to the default file system I am running on "now".
What Java needs is:
on windows system:
Path posixPath = Paths.get("/home/mystuff", FileSystem.Posix );
stays /home/mystuff/ and does not get converted to \\home\\mystuff
on linux system:
String winPath = Paths.get("c:\home\mystuff", FileSystem.Windows).toString();
stays c:\home\mystuff
and does not get converted to /c:/home/mystuff
similar to working with character sets:
URLEncoder.encode( "whatever here", "UTF-8" ).getBytes();
P.S. I also do not want to load a whole apache io jar file to do something simple either. In this case they do not have what I propose anyways.