如何在java中得到一个文件夹下的所有中文的文件名
时间: 2023-08-11 10:05:29 浏览: 37
您可以使用以下Java代码获取指定文件夹中所有中文文件的名称:
```
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class GetChineseFileNames {
public static void main(String[] args) {
String folderPath = "your/folder/path";
List<String> fileNames = getChineseFileNames(folderPath);
for (String fileName : fileNames) {
System.out.println(fileName);
}
}
public static List<String> getChineseFileNames(String folderPath) {
File folder = new File(folderPath);
File[] files = folder.listFiles();
List<String> fileNames = new ArrayList<>();
for (File file : files) {
if (file.isFile()) {
String fileName = file.getName();
if (isChinese(fileName)) {
fileNames.add(decodeFileName(fileName));
}
}
}
return fileNames;
}
public static boolean isChinese(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 0x4e00 && str.charAt(i) <= 0x9fa5) {
return true;
}
}
return false;
}
public static String decodeFileName(String fileName) {
try {
return new String(fileName.getBytes("ISO-8859-1"), StandardCharsets.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
}
```
在上述代码中,我们定义了一个 `getChineseFileNames()` 方法来获取文件夹中所有中文文件的名称。首先,我们使用 `isChinese()` 方法判断文件名是否包含中文字符。如果是,我们使用 `decodeFileName()` 方法将ISO-8859-1编码的文件名转换为UTF-8编码的文件名,并添加到 `fileNames` 列表中。最后,我们返回 `fileNames` 列表。您可以根据实际情况修改该代码以适应您的需求。