如何在Java中创建适用于这两种操作系统的文件路径的最佳解决方案。该应用程序将在这些操作系统上使用,因此我需要创建通用字符串。
例如:
对于Linux:
File folderTxt = new File("/home/romankooo/work/txt/");
对于Windows操作系统:
File folderTxt = new File("C:\\PDFMalwareDataAnalyser\\Txt\\");
或者最好的解决方案是为该操作系统生成2个jar文件。
如何在Java中创建适用于这两种操作系统的文件路径的最佳解决方案。该应用程序将在这些操作系统上使用,因此我需要创建通用字符串。
例如:
对于Linux:
File folderTxt = new File("/home/romankooo/work/txt/");
对于Windows操作系统:
File folderTxt = new File("C:\\PDFMalwareDataAnalyser\\Txt\\");
或者最好的解决方案是为该操作系统生成2个jar文件。
最好的方法是让Java像这样为您做决定
File folderTxt = new File(File.separator + "home" + File.separator + "romankooo" + File.separator + "work" + File.separator + "txt" + File.separator);
C:/PDFMalwareDataAnalyser/Txt/
而不是 C:\\PDFMalwareDataAnalyser\\Txt\\
,它仍然可以在 Windows 操作系统上正常工作。尝试这行代码,根据返回的字符串调整你的代码。
System.getproperty("os.name");
使用 System.getProperty("os.name")
获取操作系统名称,根据其设置资源路径:
String resourcePath = null;
switch (System.getProperty("os.name")) {
case "Linux": resourcePath = "/home/romankooo/work/txt/";
break;
case "Windows": resourcePath = "C:\\PDFMalwareDataAnalyser\\Txt\\";
break;
}
File.separator
,正如 @microtone 在另一个回答中所说。 - jsosnowski我个人认为最好通过系统属性传递文件夹:
java -Dfolder=C:\PDFMalwareDataAnalyser\Txt\ myapp
你可以像这样使用它:
public File folderTxt = new File(System.getProperty("folderTxt"));
或者通过程序参数传递文件夹:
java myapp C:\PDFMalwareDataAnalyser\Txt\
然后像这样使用它:
public File folderTxt = new File(args[1]);
但是如果您在代码中坚持使用常量,可以像这样使用:
public File folderTxt = new File(String.join(File.separator,"C:","PDFMalwareDataAnalyser","Txt"));
或者更新的版本是:
public File folderTxt = new File(Paths.get("C:","PDFMalwareDataAnalyser","Txt").toString());
或者您也可以读取一个属性文件并将路径存储在其中。这适用于不同的操作系统,您只需要在之前创建属性文件:
String propertyFileName = String.format("folderSettings-%s.properties", System.getProperty("os.name").replaceAll(" ","_"));
Properties p = new Properties();
try (InputStream is = getClass().getResourceAsStream(propertyFileName))
{
p.load(is);
String folderName = p.getProperty("folderName");
folderTxt = new File(folderName);
}
catch (Exception e)
{
// log if error occurs...
e.printStackTrace();
}