我有一个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
...
Run Code Online (Sandbox Code Playgroud)
Hat*_*ley 10
怎么样.substring()&.lastIndexOf()?
String file = filesFound[0];
String newFileName = file.substring(0, file.lastIndexOf("_"));
Run Code Online (Sandbox Code Playgroud)
然后,将newFileName包含直到(但不包括)最后一个“_”字符的所有内容。
Arrays.copyOf 返回一个新数组,因此您必须将其分配给 t 或一个新变量:
t = Arrays.copyOf(t, t.length - 1)
Run Code Online (Sandbox Code Playgroud)
复制阵列不会将各个部分重新连接在一起。尝试
StringBuilder builder = new StringBuilder();
for (int i = 0; i < t.length - 1; i++) {
builder.append(t[i]);
}
String joined = builder.toString();
Run Code Online (Sandbox Code Playgroud)