String path = "C:\\xxx\\a.txt";
//获取文件名之前的目录
String directoryStr = path.substring(0, path.lastIndexOf(File.separator));
System.out.println("File.separator = "+File.separator);
System.out.println("path.length() = "+path.length()+"\npath.lastIndexOf(File.separator) = "+path.lastIndexOf(File.separator));
System.out.println("directoryStr = "+directoryStr);
//获取文件名
String directoryStr2 = path.substring(path.lastIndexOf(File.separator)+1);
System.out.println(directoryStr2);
结果:
File.separator = \
path.length() = 12
path.lastIndexOf(File.separator) = 6
directoryStr = C:\xxx
a.txt