File folderTxt = new File("C:\\PDFMalwareDataAnalyser\\Txt\\");
或者,最好的解决办法是为这个操作系统生成2个jar文件。
5 个回答
0 人赞同
最好的办法是让java为你决定,就像这样
File folderTxt = new File(File.separator + "home" + File.separator + "romankooo" + File.separator + "work" + File.separator + "txt" + File.separator);
0 人赞同
你可以使用斜线字符作为两个操作系统的文件分隔符,换句话说,你可以使用C:/PDFMalwareDataAnalyser/Txt/
而不是C:\\PDFMalwareDataAnalyser\\Txt\\
,它仍然可以在Windows操作系统上工作。
0 人赞同
使用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;
0 人赞同
试试这行代码,根据返回的字符串,你可以调整你的代码
System.getproperty("os.name");
0 人赞同
我个人认为,你最好让文件夹通过系统属性传递进来。
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)