我有一个包含文件名的数组变量filesFound
。如何删除最后一个数字部分,包括其扩展名。
...
File[] filesFound = SomeUtils.findFile("xyz","c:\\")
//fileFound[0] is now "abc_xyz_pqr_27062016.csv"
//What I need is "abc_xyz_pqr" only
String[] t = filesFound[0].toString().split("_")
Arrays.copyOf(t, t.length - 1) //this is not working
...
答案 0 :(得分:5)
复制数组不会将这些部分连接在一起。试试
StringBuilder builder = new StringBuilder();
for (int i = 0; i < t.length - 1; i++) {
builder.append(t[i]);
}
String joined = builder.toString();
答案 1 :(得分:4)
Arrays.copyOf
返回一个新数组,因此您必须将其分配给t或新变量:
t = Arrays.copyOf(t, t.length - 1)
答案 2 :(得分:2)
正则表达式:
System.out.println("abc_xyz_pqr_27062016.csv");
System.out.println("abc_xyz_pqr_27062016.csv".replaceAll("_\\d+.+",""));
打印出来:
abc_xyz_pqr_27062016.csv
abc_xyz_pqr
答案 3 :(得分:0)
有点紧张..
//fileFound[0] is now "abc_xyz_pqr_27062016.csv"
String file = fileFound[0] ;
String filter = "";
int i = 0;
char [] allChars = file.toCharArray();
char oneChar ;
while(i < (file.length()-4)){//4 is .csv
oneChar = allChars[i];
if((oneChar >= 65 && oneChar <=90)||(oneChar >= 97 && oneChar <=122)|| oneChar==95){
filter += oneChar;
}
i++;
}
filter = filter.substring(0, filter.length()-1);
System.out.println(filter);
这很好用
答案 4 :(得分:-1)
.substring()
&amp; .lastIndexOf()
?
String file = filesFound[0];
String newFileName = file.substring(0, file.lastIndexOf("_"));
newFileName
将包含最后(但不包括)最后一个&#39; _&#39;炭。