java数组序列化文件,JAVA 序列化图像文件数据到byte[]数组,反序列化,写入数据后,异常...

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值