据此3rd answer ,我可以写一个这样的文件
Files.write(Paths.get("file6.txt"), lines, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
但是,当我在代码上尝试时,出现此错误:
The method write(Path, Iterable, Charset, OpenOption...) in the type Files is not applicable for the arguments (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);
最佳答案
说明
Files#write
有 3 个重载方法(参见documentation):
- 需要
Path, byte[], OpenOption...
(无字符集) - 需要
Path, Iterable<? extends CharSequence>, OpenOption...
(如List<String>
,无字符集,使用 UTF-8) - 需要
Path, Iterable<? extends CharSequence>, Charset, OpenOption...
(有字符集)
对于您的调用 ( Path, byte[], Charset, OpenOption...
),不存在匹配的版本。因此,它无法编译。
它与第一个和第二个重载不匹配,因为它们不支持 Charset
并且它与第三个重载不匹配,因为两者都不是数组 Iterable
(像 ArrayList
这样的类是), byte
也不是延长CharSequence
(String
确实如此)。
在错误消息中,您可以看到 Java 计算出的内容与您的调用最接近,不幸的是(如所解释的),它不适用于您的参数。
<小时/>解决方案
您很可能打算进行第一次重载:
Files.write(Paths.get("file6.txt"), lines,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
即无字符集。
<小时/>注释
字符集在您的上下文中没有任何意义。字符集的唯一目的是从 String
正确转换。到二进制byte[]
。但您的数据已经是二进制的,因此字符集在此之前就已到位。在你的情况下,这将是 readFileContent
中的阅读阶段.
另请注意 Files
中的所有方法默认情况下已使用 UTF-8。所以无论如何都不需要额外指定它。
当指定OpenOption
时s,您可能还想指定是否是 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);
关于java - Files#write 不适用于 byte[] 和字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59065292/