Java File Path Windows/linux
Solution 1:
The best thing is to let java decide that for you like this
publicFilefolderTxt=newFile(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");
Solution 5:
Personally I think you'd better get the folder passed in by a system property:
java -Dfolder=C:\PDFMalwareDataAnalyser\Txt\ myapp
This one you can use like this:
publicFilefolderTxt=newFile(System.getProperty("folderTxt"));
Or pass the folder by a program argument:
java myapp C:\PDFMalwareDataAnalyser\Txt\
And then use it like this:
publicFilefolderTxt=newFile(args[1]);
But if you're sticking to use constants in your code, you can use it like this:
public File folderTxt = new File(String.join(File.separator,"C:","PDFMalwareDataAnalyser","Txt"));
Or a newer version of this would be:
public File folderTxt = new File(Paths.get("C:","PDFMalwareDataAnalyser","Txt").toString());
Or you could also read a property file and store the path in that one. This would work for different OSes, you only have to create the property files before:
StringpropertyFileName= String.format("folderSettings-%s.properties", System.getProperty("os.name").replaceAll(" ","_"));
Propertiesp=newProperties();
try (InputStreamis= getClass().getResourceAsStream(propertyFileName))
{
p.load(is);
StringfolderName= p.getProperty("folderName");
folderTxt = newFile(folderName);
}
catch (Exception e)
{
// log if error occurs...
e.printStackTrace();
}
Post a Comment for "Java File Path Windows/linux"