用Java从ZIP压缩包中提取UTF-16编码的文件

发布于 2024-08-18 16:09:44 字数 795 浏览 4 评论 0原文

在代码的最后一部分,我打印了读者给我的内容。但这只是假的,我哪里错了?

public static void read_impl(File file, String targetFile) {
    // Create zipfile input stream
    FileInputStream stream = new FileInputStream(file);
    ZipInputStream zipFile = new ZipInputStream(new BufferedInputStream(stream));

    // Im looking for a specific file/entry
    while (!zipFile.getNextEntry().getName().equals(targetFile)) {
        zipFile.getNextEntry();
    }

    // Next step in api requires a reader
    // The target file is a UTF-16 encoded text file
    InputStreamReader reader = new InputStreamReader(zipFile, Charset.forName("UTF-16"));

    // I cant make sense of what this print
    char buf[] = new char[1];
    while (reader.read(buf, 0, 1) != -1) {
        System.out.print(buf);
    }
}

In the last section of the code I print what the Reader gives me. But its just bogus, where did I go wrong?

public static void read_impl(File file, String targetFile) {
    // Create zipfile input stream
    FileInputStream stream = new FileInputStream(file);
    ZipInputStream zipFile = new ZipInputStream(new BufferedInputStream(stream));

    // Im looking for a specific file/entry
    while (!zipFile.getNextEntry().getName().equals(targetFile)) {
        zipFile.getNextEntry();
    }

    // Next step in api requires a reader
    // The target file is a UTF-16 encoded text file
    InputStreamReader reader = new InputStreamReader(zipFile, Charset.forName("UTF-16"));

    // I cant make sense of what this print
    char buf[] = new char[1];
    while (reader.read(buf, 0, 1) != -1) {
        System.out.print(buf);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒儿 2024-08-25 16:09:44

我猜你出错的地方是相信该文件是 UTF-16 编码的。

如果不解码它们,您能显示一些初始字节值吗?

I'd guess that where you went wrong was believing that the file was UTF-16 encoded.

Can you show a few initial byte values if you don't decode them?

若能看破又如何 2024-08-25 16:09:44

您使用 char 数组有点毫无意义,尽管乍一看它应该可以工作。请尝试以下操作:

int c;
while ((c = reader.read()) != -1) {
    System.out.print((char)c);
}

如果这也不起作用,那么可能您得到了错误的文件,或者该文件不包含您认为的内容,或者控制台无法显示它包含的字符。

Your use of a char array is a bit pointless, though at first glance it should work. Try this instead:

int c;
while ((c = reader.read()) != -1) {
    System.out.print((char)c);
}

If that does not work either, then perhaps you got the wrong file, or the file does not contain what you think it does, or the console can't display the characters it contains.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文