JAVA automatically adapts Linux and Windows file path separators

The Linux file path separator is / , and the Windows file path separator is \ . If you are not sure which operating system the user is using during the development of the project, you need to automatically adapt the path.

It is currently known that Java provides two methods to obtain the file path separator:
File.separator
System.getProperty("file.separator")

provides a simple tool class:
[java] view plain copy
public class FilePathUtil { 
    public static final String FILE_SEPARATOR = System .getProperty("file.separator"); 
    //public static final String FILE_SEPARATOR = File.separator; 
 
    public static String getRealFilePath(String path) { 
        return path.replace("/", FILE_SEPARATOR).replace("\\", FILE_SEPARATOR); 
    } 
 
    public static String getHttpURLPath(String path) { 
        return path.replace("\\", "/"); 





Of course, you can also use the request method to get the file path:
String serverPath = request.getServletContext().getRealPath("/assets/data/templete/import/");
This method will automatically adapt the file separator to get the file in the project directory assets/data/templete/import folder, regardless of delimiter file paths.

PS: By default, if you directly write the linux path (/), tomcat can find the correct path when running under windows; but if you write the windows path (\), the following situations will occur on the linux platform:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326252981&siteId=291194637