简体   繁体   中英

How to force Java to use Unix file separators on Windows?

I have a simple code

String staticDir = f.getCanonicalPath() + "/src/main/webapp/static/";

On Windows it will return for me "C:\\Temp/src/main/webapp/static/".

How to force Java to use "/" instead of "\\"?

I have tried

System.setProperty("file.separator", "/");
String staticDir = f.getCanonicalPath() + "/src/main/webapp/static/";

but it doesn't solved issue for me.

Thank you!

Just replace the path separator with the expected one:

String dir = f.getCanonicalPath().replace(System.getProperty("file.separator"), "/")
             + "/src/main/webapp/static/";

If you can, favor Java 7+'s java.nio.file.Path . There, the notion of path separator disappears until you call toString() . But very few libraries use this and still use File or even, worse, String .

If the library you're using still does it by the mean of strings, it probably means they're splitting manually on / . Maybe it's time to tell them to upgrade?

In my case it was a bug in the library, that I use - https://github.com/yui/yuicompressor/issues/111 .

That's why all suggested solution didn't solved issue for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM