Java File Path Windows/Linux
29,781
Solution 1
The best thing is to let java decide that for you like this
File folderTxt = new File(File.separator + "home" + File.separator + "romankooo" + File.separator + "work" + File.separator + "txt" + File.separator);
Solution 2
You can use slash character as file separator for both OS, in other words you can use C:/PDFMalwareDataAnalyser/Txt/
instead of C:\\PDFMalwareDataAnalyser\\Txt\\
it will still work on Windows OS.
Solution 3
Use System.getProperty("os.name")
for obtaining os name, depends on it set path to resource:
String resourcePath = null;
switch (System.getProperty("os.name")) {
case "Linux": resourcePath = "/home/romankooo/work/txt/";
break;
case "Windows": resourcePath = "C:\\PDFMalwareDataAnalyser\\Txt\\";
break;
}
Solution 4
Try this line of code and according to the string return you can adjust your code
System.getproperty("os.name");
Related videos on Youtube
Author by
bilinxe
Updated on March 11, 2020Comments
-
bilinxe about 4 years
what is the best solution to create file path in Java for this two OS. Application will be used for this os , the i need to create universal String.
for example : For Linux:
public File folderTxt = new File("/home/romankooo/work/txt/");
For Windows:
public File folderTxt = new File("C:\\PDFMalwareDataAnalyser\\Txt\\");
Or is the best solution to generate 2 .jar files for this OS.
Thank a lot guys.
-
BalusC about 8 yearsAnswer depends on the purpose of the folder. Creating temporary files? Providing configuration files? Reading and writing data files? Storing user preferences? Etcetera. For each of those purposes there are well defined cross platform solutions.
-
-
bilinxe about 8 yearsOkey, thanks..in linux run this app good bud in windows i dont can change write permissions to folder
-
jsosnowski over 6 yearsBad approach. Better use everywhere slash ('/') or
File.separator
as @microtone said here in other answer. -
jsosnowski over 6 yearsIt is good if the file path is visible somewhere. If user can't see the path then simpler solution is to use slash '/' everywhere.