use*_*403 5 java eclipse base64
有人可以向我解释为什么下面的第二个 println 语句没有打印任何内容吗?即使我使用 encodeToString() 方法而不是 encode() 方法,我仍然无法打印 Base64 编码的字符串。编码的字符串不为空,因为我可以使用它的 length() 方法进行验证。我尝试了一个不同的文件,一个二进制文件,但问题仍然存在。
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class Test {
public static void main(String... args) {
try {
byte[] content = Files.readAllBytes(Paths.get("D:\\config.properties"));
System.out.println(content.length); // correctly prints the length
byte[] encoded = Base64.getEncoder().encode(content);
System.out.println(new String(encoded)); // prints nothing
content = Base64.getDecoder().decode(encoded);
System.out.println(new String(content)); // prints original content
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
这个问题只在我在 Eclipse 中运行程序时存在。当我从命令提示符运行它时,可以打印出 Base64 编码的字符串。
当调用 new String(encoded) 来打印编码的字节数组时,控制台不会打印任何内容。这是因为 new String(byte[]) 构造函数期望字节数组是有效的字符编码,但编码后的字节数组不一定是有效的字符编码。您可以使用 Arrays.toString(encoded) 或 Base64.getEncoder().encodeToString(content) 来打印编码的字节数组,而不是使用 new String(encoded)。
如果这在一种环境中有效,而在另一种环境中无效,则可能存在不同的默认编码。检查您的环境设置。文件编码可以这样设置:
System.setProperty("file.encoding", "UTF-8");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
756 次 |
| 最近记录: |