简体   繁体   中英

Is there a clean and easy way to make file path strings in Java OS agnostic?

I've made a class which takes in any string of one format (eg. UNIX) and coverts into whatever OS the java is running on.

enum OperatingSystem {
    WINDOWS,
    LINUX;

    static OperatingSystem initOS() {
        String osName = System.getProperty("os.name");

        switch (osName) {
            case "Windows 8.1":
               return WINDOWS;
            case "Linux":
               return LINUX;
            default:
                return LINUX;
        }
    }

}



public class OSSP {
    public static final OperatingSystem USEROS = OperatingSystem.initOS();


//    Auxilarry methods to return OSAppropriateString
    private static String makeLinuxCompatible(String[] path) {
        return String.join("/", path);
    }

    private static String makeWindowsCompatible(String[] path) {
        return String.join("\\", path);
    }

    public static String getOSSpecificPath(String path) {
        String[] splittedPath = {""}, subpath = {""};
        String finalPath = "";
        if(path.contains("\\")) {
            splittedPath = path.split("\\\\",-1);
        }
        else if (path.contains("/")) {
            splittedPath = path.split("/",-1);
        }

        if (USEROS == OperatingSystem.LINUX) {
            finalPath =  makeLinuxCompatible(splittedPath);
        }
        else if (USEROS == OperatingSystem.WINDOWS) {
            finalPath =  makeWindowsCompatible(splittedPath);
        }
        return finalPath;
    }
}

This is fine if you're working on small code and you'd have to do it often.

But, I have a huge GUI code where I'd have to insert this function wherever there is path specified in the program. Is there a way to make path like strings automatically OS specific?

Otherwise a setting where any OS function which takes a path automatically changes accordingly under the hood.

Use Path with Files .

Path path = Paths.get(".../...");
Path path = Paths.get("...", "...");
// path.resolve, relativize, normalize, getFileSystem

This class is a generalisation of File which is only for pure file system files. A path might point in a subdirectory of a .zip using a zip file system and so on.

For established File using APIs one can use Path.toFile() and File.toPath() .

Paths.get is very versatile, also due to the Posix compatibility of Windows (accepting / besides \\ ). You can get a canonical normalized path anyway.

path.toRealPath()

The old File you can use:

String separator = File.separator;

For a path which can point to different file systems :

String separator = path.getFileSystem().getSeparator();

In general Path is a nifty class storing the name parts, the file system. It covers many aspects like ".." .

The best way to deal with this kind of situation is to not try to detect the OS since that can be rather hit-or-miss. Instead the Java API does provide a way to tell you what character to use as a path separator. Look at this API documentation on File: https://docs.oracle.com/javase/8/docs/api/java/io/File.html and look for the specific static field separator . I would highly suggest you parse the path using the File class then if you need the path as an string simply call toURI().toString() to get it into a format that the OS can recognize.

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