png 二进制文件的 base64 编码不起作用 JDK 11.0.3+7 Eclipse 4.11.0
base64 encoding of png binary doesn't work JDK 11.0.3+7 Eclipse 4.11.0
以下代码
import java.util.Base64;
try (final InputStream fis = new FileInputStream(new File("foobar.png"))) {
final String str = Base64.getEncoder().encodeToString(fis.readAllBytes());
System.out.println("+++" + str + "+++"); // prints nothing!
System.out.println("+++" + str.length() + "+++"); // +++34500+++
System.out.println("+++" + str.isBlank() + "+++"); // +++false+++
try (final OutputStream os = new FileOutputStream(new File("foobar.txt"))) {
os.write(str.getBytes()); // empty file!
}
final String str2 = "foobar";
try (final OutputStream os2 = new FileOutputStream(new File("foobar2.txt"))) {
os2.write(Base64.getEncoder().encodeToString(str2.getBytes()); // This works!
}
}
第一次调用 System.out.println
时不打印任何内容。怎么了?此外,当我用 base64 编码的字符串写入文件时,文件为空。
当我在没有使用 base64 编码的情况下将所有读取的字节写回文件系统时,这两个文件是相等的。所以,没关系。但是编码有什么问题?
foobar.png
在文件系统上有 26 KiB。
采用JDK11.0.3+7
日食:2019-03 (4.11.0)
解决方案
感谢罗伯特。这显然只是我的 Eclipse 版本中的一个 显示问题。
以下代码
import java.util.Base64;
try (final InputStream fis = new FileInputStream(new File("foobar.png"))) {
final String str = Base64.getEncoder().encodeToString(fis.readAllBytes());
System.out.println("+++" + str + "+++"); // prints nothing!
System.out.println("+++" + str.length() + "+++"); // +++34500+++
System.out.println("+++" + str.isBlank() + "+++"); // +++false+++
try (final OutputStream os = new FileOutputStream(new File("foobar.txt"))) {
os.write(str.getBytes()); // empty file!
}
final String str2 = "foobar";
try (final OutputStream os2 = new FileOutputStream(new File("foobar2.txt"))) {
os2.write(Base64.getEncoder().encodeToString(str2.getBytes()); // This works!
}
}
第一次调用 System.out.println
时不打印任何内容。怎么了?此外,当我用 base64 编码的字符串写入文件时,文件为空。
当我在没有使用 base64 编码的情况下将所有读取的字节写回文件系统时,这两个文件是相等的。所以,没关系。但是编码有什么问题?
foobar.png
在文件系统上有 26 KiB。
采用JDK11.0.3+7
日食:2019-03 (4.11.0)
解决方案
感谢罗伯特。这显然只是我的 Eclipse 版本中的一个 显示问题。