Issue
The following code
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!
}
}
doesn't print anything it the first call of System.out.println
. What's wrong? Moreover when I write a file with the base64 encoded string the file is empty.
When I write all the read bytes back to file system without base64 encoding than the two files are equal. So, that's okay. But what's wrong with the encoding?
foobar.png
has 26 KiB on file system.
Adopt JDK 11.0.3+7
Eclipse: 2019-03 (4.11.0)
Solution
Thanks to Robert. This is obviously only a display problem in my Eclipse version.
Solution
Most likely you are executing this Java code in an IDE like Eclipse.
Eclipse for example has a bug that lines that are too long are not printed: 541104/23406.
In your case the base64 encoded String has 34500 character which is large enough to trigger this bug.
The most recent version of Eclipse (2020-03) using OpenJDK 1.0.7 on Windows 10 64bit seem to be capable of displaying some more characters (e.g. in a quick test a line with 67000 characters was visible).
But don't forget to increase the Console buffer size
in Eclipse settings (Run/Debug -> Console).
Answered By - Robert