小编use*_*914的帖子

尝试将String编码/解码为Base64时出错

我需要从字节数组进行Base64编码,而不是另一个字节数组.但当我解码它时,我得到例外.这是代码

我正在尝试使用Base64编码将字节数组编码为字符串.当我编码时,它似乎工作,但当我解码它会引发异常.我究竟做错了什么?

import org.springframework.security.crypto.codec.Base64;

byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9};
String stringToStore = Base64.encode(bytes).toString();
byte[] restoredBytes = Base64.decode(stringToStore.getBytes());
Run Code Online (Sandbox Code Playgroud)

这是我得到的例外:

org.springframework.security.crypto.codec.InvalidBase64CharacterException: Bad Base64 input character decimal 91 in array position 0
at org.springframework.security.crypto.codec.Base64.decode(Base64.java:625)
at org.springframework.security.crypto.codec.Base64.decode(Base64.java:246)
Run Code Online (Sandbox Code Playgroud)

java base64

16
推荐指数
3
解决办法
7万
查看次数

写入ObjectOutputStream并返回垃圾

我将许多对象放入流中,然后从中获取字节数组,然后读取所有内容.前两个数据到达状态良好,然后我得到零,然后是EOF异常.为什么?

try {
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
     objectOutputStream.writeObject("abcdef");
     objectOutputStream.writeInt(1);
     objectOutputStream.writeObject(new byte[]{1,2,3,4,5,6,7,8});
     objectOutputStream.writeInt(2);
     objectOutputStream.writeObject(new byte[]{11,12,13,14,15,16,17,18});
     objectOutputStream.close();


     byte[] original = byteArrayOutputStream.toByteArray();
     System.out.println(Arrays.toString(original));

     byte[] b=new byte[8];
     ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(original));
     String s= (String) objectInputStream.readObject(); // works fine
     objectInputStream.readInt(); // works fine

     objectInputStream.read(b); // why it reads zeroes instead of [1,2,3,4,5,6,7,8]?
     System.out.println(Arrays.toString(b));
     int length = objectInputStream.readInt(); // EOF unexpectedly reached, why?
     objectInputStream.read(b);
}
catch (IOException e) {
     e.printStackTrace();
} catch (ClassNotFoundException e) {
     e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

例外: …

java

1
推荐指数
1
解决办法
1170
查看次数

标签 统计

java ×2

base64 ×1