gpt4 book ai didi

Java 8 Base64 编码(基本)不再添加新行。我怎样才能重新实现这个?

转载 作者:行者123 更新时间:2023-12-01 16:57:20 25 4
gpt4 key购买 nike

我基本上有完全相同的相反问题

new-line-appending-on-my-encrypted-string

似乎旧的 Java Base64 实用程序在返回字符串时总是每 76 个字符添加新行,但使用以下代码,我没有得到我需要的那些中断。

    Path path = Paths.get(file);
byte[] data = Files.readAllBytes(path);
String txt= Base64.getEncoder().encodeToString(data);

有没有一种简单的方法可以告诉编码器添加换行符?

我尝试实现一个字符串构建器来插入换行符,但它最终改变了整个输出(我将文本从java控制台复制到HxD编辑器,并与我已知的带有换行符的工作“BLOB”进行比较)。

    String txt= Base64.getEncoder().encodeToString(data);

//Byte code for newline
byte b1 = 0x0D;
byte b2 = 0x0A;

StringBuilder sb = new StringBuilder();
for (int i = 0; i < txt.length(); i++) {
if (i > 0 && (i % 76 == 0)) {
sb.append((char)b1);
sb.append((char)b2);

}

sb.append(txt.charAt(i));
}

编辑(回答问题):

这不是最容易解释的事情,但是当我不使用字符串生成器时,编码的输出将像这样开始:

AAAAPAog4lBVgGJrT2b+mQVicHN3d////////3hhcDJiLWVtMjUwLWVtMjUwLWRldjA0NTUAAAAAAA

但我希望它看起来像这样:

AAAAPAog4lBVgGJrT2b+mQVicHN3d////////3hhcDJiLWVtMjUwLWVtMjUwLWRldjA0NTUAAAAA..AA

如您所见,“..”代表 0x0D 和 0X0A 或换行符,它插入在第 76 个字符处(这是旧的 Base64 会输出的内容)。

但是,当我在第 76 个字符后附加字节 b1 和 b2(换行符)时,输出变为:

BPwAFHwA0CUFOG8AgDRCAAIlQgAAJUIAAhUfNEIAAiUkmw/0fADQFSInART/ADUlfADQFQE0fADQ..

所以看起来“..”是在正确的位置,但它之前的一切都不同。

谢谢!

最佳答案

您需要 getMimeEncoder 来代替:

MIME

Uses the "The Base64 Alphabet" as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return '\r' followed immediately by a linefeed '\n' as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.

(强调我的)

请注意,编码方案在其他方面与 getEncoder 中的基本编码器相同 - 它们均源自 RFC 2045。

关于Java 8 Base64 编码(基本)不再添加新行。我怎样才能重新实现这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30961979/

25 4 0
文章推荐: delphi - fmx delphi berlin 如何更改 Tgrid 行中的字体颜色
文章推荐: java - 删除前导 0 直至小数点
文章推荐: objective-c - 在 objective-c 中的DTCoreText中并排放置两个内联
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com