Object before = "";
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(os);
oo.writeObject(before);
oo.close();
String serialized = os.toString("UTF-8");
ByteArrayInputStream is = new ByteArrayInputStream(serialized.getBytes("UTF-8"));
try(ObjectInputStream io = new ObjectInputStream(is)) {
Object after = io.readObject();
System.err.println("Object deserialization successful.");
} catch (Exception e) {
System.err.println("Object deserialization error.");
System.err.println("Type being serialized: " + before.getClass());
System.err.println("Serialization as bytes: " + Arrays.toString(serialized.getBytes("UTF-8")));
e.printStackTrace();
}
所以我已经得到了一些代码,我正在使用它来将一个对象序列化为java.lang.String并在以后对其进行反序列化。我使用对象流来执行对象写入/读取和字节数组流来进行字符串处理。但是当我尝试在序列化对象周围构造一个ObjectInputStream时,我得到一个StreamCorruptedException,声称有一个"无效的流标题"。
上面的代码示例是我能找到的最基本的代码片段,可以重现我的问题(而且非常简单!)。据我所知,我完全对称地做了一切:
但是在第4步,在ObjectInputStream的构造函数中,程序崩溃并出现StreamCorruptedException。我非常感到困惑,因为这些字节实际上是只是由ObjectOutputStream生成的!
答案 0 :(得分:2)
不要将byte[]
转换为String
和ByteArrayOutputStream
,这将解释特殊(宽)字符。相反,只需直接使用ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
中的字节。像,
<html>
<head>
<title></title>
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "blog_samples";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$rows_count = count($_POST["name"]);
for($i=0;$i<$rows_count;$i++){
// PREVENTING SQL INJECTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$employee_name = mysqli_real_escape_string($conn,$_POST["employee_name"][$i]);
$name = mysqli_real_escape_string($conn,$_POST["name"][$i]);
$code = mysqli_real_escape_string($conn,$_POST["code"][$i]);
$quantity = intval($_POST["quantity"][$i]);
$price = mysqli_real_escape_string($conn,$_POST["price"][$i]);
$sql = "INSERT INTO order_table ( employee_name, name, code, quantity, price)
VALUES ('$employee_name', '$name', '$code', '$quantity', '$price')";
$query = mysqli_query($conn,$sql);
if(mysqli_affected_rows($conn)>0) {
echo "Record add successfully";
$to = "xgrh@gmail.com";
$subject = "Supplies";
$headers = "From: user@gmail.com";
$message =
"employee_name: " . $employee_name . "
" ."name: ". $name ."
". "code: " . $code . "
" ."quantity: ". $quantity . "
". "price: " . $price . "";
mail($to,$subject,$message,$headers);
}
}
?>
</body>
</html>