JAVA 序列化图像文件数据到byte[]数组,反序列化,写入数据后,错误
我想在Client将E:\\JAVA\\Serializable.bmp的图像文件据数据分多次写进数组,多次序列化传送出去,然后
在Server 那边反序列后写进E:\\JAVA\\B\\Serializable.bmp。运行后,两个文件的字节数一样,但显示效果却不同,求解答,谢谢..
Socket client = null;
ObjectOutputStream objOut = null;
try {
client = new Socket("127.0.0.1", 9999);
OutputStream os = client.getOutputStream();
objOut = new ObjectOutputStream(os);
File file=new File("E:\\JAVA\\Serializable.bmp");
if (file.exists()) {
InputStream ins = new FileInputStream(file);
byte[] datas = new byte[1024];
int size = 0;
while((size = ins.read(datas))==1024){
System.out.println(size);
objOut.writeObject(datas);
objOut.flush();
}
System.out.println(size);
byte[] datasEnd = new byte[size];
objOut.writeObject(datasEnd);
objOut.flush();
ServerSocket server = null;
ObjectInputStream objIn = null;
ObjectOutputStream objOut = null;
try {
server = new ServerSocket(9999);
Socket socket = server.accept();
InputStream is = socket.getInputStream();
objIn = new ObjectInputStream(is);
File file = new File("E:\\JAVA\\B\\Serializable.bmp");
OutputStream ous = new FileOutputStream(file,true);
while(true){
Object data = objIn.readObject();
if(data instanceof byte[]){
byte[] datas = (byte[])data;
ous.write(datas);
ous.flush();
}
}
Java
socket
------解决方案--------------------
你现在的做法是把一张图片分割成好几段,然后分段发送。
这样那边接受之后在拼接的话肯定容易出现问题。
你可以把图片改成txt试试,看看文档的输出顺序对不对。
想要得到标准的效果应该是分割读一张图片,但是把这些byte写入到一个流里面,然后一起发送。
------解决方案--------------------
public class Test {
public static void main(String[] args) throws Exception {
new Thread() {
public void run() {
try {
Test.server();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
new Thread() {
public void run() {
try {
Test.client();
;
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
public static void server() throws Exception {
ServerSocket server = new ServerSocket(7788);
Socket client = server.accept();
DataInputStream dis = new DataInputStream(new BufferedInputStream(client.getInputStream()));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:/test.jpg"));
long fileSize = dis.readLong();
long count = 0;
int len = -1;
byte[] buff = new byte[4096];
while (count
len = dis.read(buff);
bos.write(buff, 0, len);