提问人:Rk1659 提问时间:10/6/2023 更新时间:10/6/2023 访问量:93
无法使用 java 读取文件名中的非 UTF8 字节,导致文件统计失败
Unable to read non-UTF8 bytes in the filename using java, causing failure in stat of file
问:
我有一个目录中的文件列表,这些文件名的名称中包含非 utf8 字符。当我使用 java NIO 库从目录中读取这些文件名并列出文件时,它无法读取正确的名称。将通过迭代 DirectoryStream 创建的路径对象将替换所有对应于“?”的非 UTF8 字符。有没有办法使用 java 正确读取这些文件名,这样我就可以使用给定目录中的文件名列表并对给定目录中的每个文件执行统计。\357\277\275
我编写了一个示例 java 代码,它使用 NIO 库并尝试列出目录中的所有实体。以下是我的代码:
public class FileIteration {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the directory path: ");
String directoryPathStr = scanner.nextLine();
Path directoryPath = Paths.get(directoryPathStr);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directoryPath)) {
Iterator<Path> iterator = directoryStream.iterator();
while (iterator.hasNext()) {
Path entry = iterator.next();
String fileName = entry.getFileName().toString();
//String decodedFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
System.out.println("File: " + fileName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是一个带有字节的示例文件名,它应该被打印和读取,但我正在进入我的路径对象,您可以将其替换为字节8000124463972718\314H2\376\=M\3230U\317\313S\=
8000124463972718ÌH2þ=MÓ0UÏËS=
8000124463972718?H2?=M?0U??S=
\357\277\275
我还尝试了不同的 API,它们也观察到了同样的问题,例如我也尝试过:
public static void printPathsUsingFileWalk(String dir, int depth) throws IOException {
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
stream.forEach(path -> System.out.println("File name (using stream)"+path));
}
}
这也失败了。
文件名的编码似乎是 ISO-8859-1,而这些 java API 似乎期望它们是 UTF8。 为了确保我清楚地回答我的问题,问题不在于读取文件的内容,而在于从目录中读取文件名。由于我在尝试列出文件时得到了错误的字符,因此我无法对某些文件执行统计。
答: 暂无答案
评论