这是作为字符串的输入:
"C:\jdk1.6.0\bin\program1.java"
我需要输出:
Path-->C:\jdk1.6.0\bin\
file--->program1.java
extension--->.java
注意反斜杠字符“\”。我很容易输出“/”。
这是作为字符串的输入:
"C:\jdk1.6.0\bin\program1.java"
我需要输出:
Path-->C:\jdk1.6.0\bin\
file--->program1.java
extension--->.java
注意反斜杠字符“\”。我很容易输出“/”。
File类提供了您所需的一切:
File f = new File("C:\\jdk1.6.0\\bin\\program1.java");
System.out.println("Path-->" + f.getParent());
System.out.println("file--->" + f.getName());
int idx = f.getName().lastIndexOf('.');
System.out.println("extension--->" + ((idx > 0) ? f.getName().substring(idx) : "") );
编辑:感谢Dave指出,如果File.getName不包含'.',String.lastIndexOf将返回-1。
lastIndexOf()
。 - John GiottaFile
以增强其行为,正如我所展示的那样。 - Dave Jarvis如果路径(如果是通过编程方式生成的)返回了双斜杠,则需要进行补偿。
//Considering that strPath holds the Path String
String[] strPathParts = strPath.split("\\\\");
//Now to check Windows Drive
System.out.println("Drive Name : "+strPathParts[0]);
由于Java的File
类不支持探测文件扩展名,我建议您创建一个File
的子类来提供这个功能:
package mypackage;
/**
* Enhances java.io.File functionality by adding extension awareness.
*/
public class File extends java.io.File {
/**
* Returns the characters after the last period.
*
* @return An empty string if there is no extension.
*/
public String getExtension() {
String name = getName();
String result = "";
int index = name.lastIndexOf( '.' );
if( index > 0 ) {
result = name.substring( index );
}
return result;
}
}
现在只需将您的文件版本替换为Java版本即可,与Kurt的答案结合使用,即可获得所需的一切。
请注意,使用子类是理想的,因为如果您想要更改行为(由于不同操作系统使用不同的扩展分隔符令牌),则只需更新单个方法,整个应用程序就可以继续工作。(或者如果您需要修复错误,例如尝试执行str.substring(-1)
。)
换句话说,如果您在代码库中的多个位置提取文件扩展名,则犯了一个错误。
进一步说,如果您想要完全抽象文件类型的知识(因为某些操作系统可能不使用.
分隔符),则可以编写:
/**
* Enhances java.io.File functionality by adding extension awareness.
*/
public class File extends java.io.File {
public File( String filename ) {
super( filename );
}
/**
* Returns true if the file type matches the given type.
*/
public boolean isType( String type ) {
return getExtension().equals( type );
}
/**
* Returns the characters after the last period.
*
* @return An empty string if there is no extension.
*/
private String getExtension() {
String name = getName();
String result = "";
int index = name.lastIndexOf( '.' );
if( index > 0 ) {
result = name.substring( index );
}
return result;
}
}
File file = new File( "myfile.txt" );
if( file.isType( "png" ) ) {
System.out.println( "PNG image found!" );
}
String.split()
不是编写此功能的正确方法。你真的应该使用已经提到的indexOf()
。 - Dave Jarvis