java - 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);
解决方案
解释
该方法有 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
(类似ArrayList
is 的类),也不是byte
extend CharSequence
( String
)。
在错误消息中,您可以看到 Java 计算出的与您的调用最接近的匹配,不幸的是(如解释的那样),它不适用于您的参数。
解决方案
您很可能打算进行第一次重载:
Files.write(Paths.get("file6.txt"), lines,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
即没有字符集。
笔记
字符集在您的上下文中没有意义。charset 的唯一目的是正确转换 fromString
到 binary 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);
推荐阅读
- javascript - Chrome 76 更新后如何避免在隐身模式下请求通知权限?多少秒后通知被拒绝?
- microsoft-teams - Microsoft Teams:了解 Web 应用程序和机器人示例
- c# - c# 如何添加基于布尔值的自定义验证
- reactjs - 为什么不在redux上添加层
- css - 如何让 SVG 动画在跨浏览器中工作
- unit-testing - 如果定义了“test-ns-hook”,“lein test :only foo.bar.test/testme”没有使用“testme”功能?
- xslt - 获取节点级别
- magento2 - 为什么将 Magento2 样本数据中的 Luma Thema 样本图像扩展到自定义主题时不可见?
- c++ - 调用复制构造函数的两种方式有什么区别?
- java - Selenium WebDriver:如何在 testNG 中为失败的测试用例执行完整的测试