首页 > 解决方案 > Files#write 不适用于 byte[] 和 charset

问题描述

根据这第三个答案,我可以写一个这样的文件

Files.write(Paths.get("file6.txt"), lines, utf8,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);

但是,当我在我的代码上尝试它时,我收到了这个错误:

Files 类型中的 write(Path, Iterable, Charset, OpenOption...) 方法不适用于参数 (Path, byte[], Charset, StandardOpenOption)

这是我的代码:

    File dir = new File(myDirectoryPath);
    File[] directoryListing = dir.listFiles();
    if (directoryListing != null) {
        File newScript = new File(newPath + "//newScript.pbd");     
            if (!newScript.exists()) {
                newScript.createNewFile();
            }
        for (File child : directoryListing) {

            if (!child.isDirectory()) {
                byte[] content = null;
                Charset utf8 = StandardCharsets.UTF_8;

                content = readFileContent(child);
                try {

                    Files.write(Paths.get(newPath + "\\newScript.pbd"), content,utf8,
                            StandardOpenOption.APPEND); <== error here in this line.

                } catch (Exception e) {
                    System.out.println("COULD NOT LOG!! " + e);
                }
            }

        }
    }

请注意,如果将我的代码更改为喜欢它的工作并将其写入文件(删除 utf8)。

                    Files.write(Paths.get(newPath + "\\newScript.pbd"), content,
                            StandardOpenOption.APPEND);

标签: javafilefile-ionio

解决方案


解释

该方法有 3 个重载Files#write(请参阅文档):

  • 需要Path, byte[], OpenOption...(无字符集)
  • 需要Path, Iterable<? extends CharSequence>, OpenOption...(例如List<String>,没有字符集,使用 UTF-8)
  • 需要Path, Iterable<? extends CharSequence>, Charset, OpenOption...(有字符集)

对于您的调用 ( Path, byte[], Charset, OpenOption...),不存在匹配的版本。因此,它不会编译。

它不匹配第一个和第二个重载,因为它们不支持,Charset并且它不匹配第三个重载,因为既不是数组Iterable(类似ArrayListis 的类),也不是byteextend CharSequence( String)。

在错误消息中,您可以看到 Java 计算出的与您的调用最接近的匹配,不幸的是(如解释的那样),它不适用于您的参数。


解决方案

您很可能打算进行第一次重载:

Files.write(Paths.get("file6.txt"), lines,
    StandardOpenOption.CREATE, StandardOpenOption.APPEND);

即没有字符集。


笔记

字符集在您的上下文中没有意义。charset 的唯一目的是正确转换 fromString到 binary byte[]。但是您的数据已经是二进制的,因此字符集在此之前就已到位。在您的情况下,这将是readFileContent.

另请注意,Files默认情况下所有方法都使用 UTF-8。所以无论如何都不需要额外指定它。

在指定OpenOptions 时,您可能还想指定它是StandardOpenOption.READ还是StandardOpenOption.WRITE模式。该Files#write方法默认使用:

WRITE
CREATE
TRUNCATE_EXISTING

所以你可能想用

WRITE
CREATE
APPEND

例子

以下是一些关于如何在 UTF-8 中完全读取和写入文本和二进制文件的片段:

// Text mode
List<String> lines = Files.readAllLines(inputPath);
// do something with lines
Files.write(outputPath, lines);

// Binary mode
byte[] content = Files.readAllBytes(inputPath);
// do something with content
Files.write(outputPath, content);

推荐阅读