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
Asked
Active
Viewed 45 times
-1
-
1You could make it user-configurable. – Federico klez Culloca Mar 29 '22 at 13:05
-
For long-term storage of application data, see https://stackoverflow.com/questions/35388882/find-place-for-dedicated-application-folder. – VGR Mar 29 '22 at 13:38
2 Answers
1
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)

Aman Chauhan
- 66
- 2
0
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"));
}

Oussama ZAGHDOUD
- 1,767
- 5
- 15