Home > Net >  regarding java file system?
regarding java file system?

Time:03-29

I am new to the java file system.I store the serializable object in some file location for example d:\my files\file.txt(location is hardcoded).what should I do so that it will work on all the platforms(Linux, Windows, and UNIX).Thanks in advance

CodePudding user response:

If you are trying to save files related to the program, you could use a relative path and '/' should work as a path separator across all platforms.

If for some reason you definitely want absolute paths, you'll need to detect system os using System.getProperty("os.name") refer https://www.baeldung.com/java-detect-os and you can store os specific hard coded paths like

HashMap<String, String> osPathMap= new HashMap<>();
osPathMap.put("Windows 10", "d:\my files\file.txt");
osPathMap.put("Linux", "Some linux path");

and get the path using osPathMap.get(os_name)

CodePudding user response:

You can use System.getProperty with the parameters : user.dir or user.home , they give you the working directory path and the user home directory path on String format independently with the OS :

public static void main(String[] args) {
        // print the path of the working directory
         System.out.println(System.getProperty("user.dir"));
         // print the path of the user directory 
         System.out.println(System.getProperty("user.home"));
}
  • Related