【发布时间】:2017-06-30 10:28:45
【问题描述】:
我正在使用反射来获取一个包含字符串作为值的对象。然后我将此对象转换为字节数组并保存到文件中。 当我打开文件时,在预期的字符串前面附加了一些额外的字符。
FileOutputStream fos = new FileOutputStream("C:\\Temp\\test.txt");
Object obj = new String("Hello World"); //replaced reflection code with string object ,still not working
fos.write(toByteArray(obj));
fos.close();
public static byte[] toByteArray(Object obj) throws IOException {
byte[] bytes = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
} finally {
if (oos != null) {
oos.close();
}
if (bos != null) {
bos.close();
}
}
return bytes;
}
文件中的输出:
文件中的预期输出:
Hello World
我不知道为什么这个额外的字符出现在我的原始字符串前面,同时将对象转换为字节数组。大家能帮我看看吗
【问题讨论】:
标签: java arrays string object byte