Java中已知window下任意文件名,如何返回该文件的扩展名。
时间: 2023-06-04 20:06:40 浏览: 110
可以使用Java的String类中的lastIndexOf()与substring()方法来获取文件扩展名。示例代码如下:
String filename = "test.docx";
String extension = filename.substring(filename.lastIndexOf(".")+1);
这样就可以获取到文件名为 "test.docx" 的扩展名 "docx"。
相关问题
已知window下任意文件名,返回该文件的扩展名。。java
文件扩展名可以通过Java的File类的getName()方法和lastIndexOf()方法来获取。例如:
```
import java.io.File;
public class GetFileExtension {
public static void main(String[] args) {
String fileName = "example.txt";
File file = new File(fileName);
if (file.exists()) {
String extension = fileName.substring(fileName.lastIndexOf("."));
System.out.println("File Extension: " + extension);
} else {
System.out.println("File does not exist.");
}
}
}
```
你也可以让用户输入文件名,然后动态获取文件扩展名。
已知window下任意文件名,返回该文件的扩展名。
可以使用字符串函数和文件操作函数来实现,具体代码如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string filepath = "C:\\Users\\test\\myfile.txt";
string extension;
size_t dot_pos = filepath.find_last_of(".");
if (dot_pos != string::npos)
{
extension = filepath.substr(dot_pos + 1);
cout << "File extension: " << extension << endl;
}
else
{
cout << "Invalid file path!" << endl;
}
return 0;
}
在上述代码中,我们首先定义了一个文件路径字符串 filepath,其中包含了文件名和扩展名。然后,使用字符串函数 find_last_of() 来查找最后一个点号的位置,如果找到了,就将点号后面的字符串作为扩展名,输出到屏幕上。如果没找到点号,就说明文件路径不正确,输出错误信息。