java为每个平台获得正确的斜杠
我有一个JFilechooser来选择文件名和路径来存储一些数据。但是我还想在相同的路径中存储一个额外的文件,相同的名称但不同的扩展名。因此:
File file = filechooser.getSelectedFile();
String path = file.getParent();
String filename1 = file.getName();
// Check the extension .ext1 has been added, else add it
if(!filename1.endswith(".ext1")){
filename2 = filename1 + ".ext2";
filename1 += ".ext1";
}
else{
filename2 = filename1;
filename2 = filename2.substring(0, filename2.length-4) + "ext2";
}
// And now, if I want the full path for these files:
System.out.println(path); // E.g. prints "/home/test" withtout the ending slash
System.out.println(path + filename1); // E.g. prints "/home/testfilename1.ext1"
当然,我可以在两个字符串中间加上“//”,但我希望它是独立于平台的,并且在Windows中它应该是“\”(即使Windows路径文件c:\Us\\Test/FielNeM.Ext1可能会工作)。p>
我可以想出许多肮脏的方法来做这件事,这会让我的python开发人员大哭一场,但是哪一种方法最干净、最花哨呢
# 1 楼答案
你可以使用:
# 2 楼答案
可以使用File类中的常量:
或者对于你的
path + filename1
你可以# 3 楼答案
只需使用File类: