我正在使用反射來獲取包含字符串作爲值的對象。然後我將此對象轉換爲字節數組並保存到文件。 當我打開文件時,在預期的字符串前面添加了一些額外的字符。將java對象轉換爲字節數組時發生的問題
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
我不知道爲什麼這個額外的字符出現在我的原始字符串的前面,而將對象轉換爲字節數組。你們可以幫我在這裏嗎