创建一个类来表示文件名和路径
/** * This class assumes that the string used to initialize * fullPath has a directory path, filename, and extension. * The methods won't work if it doesn't. */ /**来自 N o w J a v a . c o m - 时代Java**/ class Filename { private String fullPath; private char pathSeparator, extensionSeparator; public Filename(String str, char sep, char ext) { fullPath = str; pathSeparator = sep; extensionSeparator = ext; } public String extension() { int dot = fullPath.lastIndexOf(extensionSeparator);//时 代 J a v a 提 供 return fullPath.substring(dot + 1); } // gets filename without extension public String filename() { int dot = fullPath.lastIndexOf(extensionSeparator); int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(sep + 1, dot); } public String path() { int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(0, sep); } } public class FilenameDemo { public static void main(String[] args) { final String FPATH = "/home/user/index.html"; Filename myHomePage = new Filename(FPATH, '/', '.'); System.out.println("Extension = " + myHomePage.extension()); System.out.println("Filename = " + myHomePage.filename()); System.out.println("Path = " + myHomePage.path()); } }