【发布时间】:2019-11-27 07:41:15
【问题描述】:
按照这个3rd answer,我可以写一个这样的文件
Files.write(Paths.get("file6.txt"), lines, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
但是当我在我的代码上尝试它时,我得到了这个错误:
方法write(Path, Iterable, Charset, 文件类型中的 OpenOption...) 不适用于参数 (路径, 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);
【问题讨论】:
-
像
byte[]这样的数组不是Iterable。 -
您很可能打算调用此方法docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/… 即没有字符集。
-
它不被视为Iterable,但与您的调用最接近的方法是具有Iterable的版本。但是字节数组并不适用。您想要采用
byte[]的变体,但该变体不采用字符集。因为如果数据已经是二进制的,字符集就没有意义了。因为字符集的唯一目的是从String正确转换为二进制byte[]。你之前已经这样做了。 -
是的,因为字符集在这种情况下毫无意义。需要指定字符集从字符串到二进制的位置,即在您的阅读阶段。请注意,
Files中的所有方法都默认使用 UTF-8,因此无需指定。 -
@Zabuza 好的,谢谢,你很有帮助,请提供它作为接受的答案。