我正在编写一个允许从服务器下载pdf文件的应用程序。在我的服务器端,由于pdfview库的原因,我得到了pdf文件的字节缓冲区。我使用字节缓冲区填充字节数组,然后使用DataOutputStream发送字节数组。使用Java套接字发送字节数组
大多数情况下,我在客户端获得了很好的数据,但有时我得到的数组中填充了随机数,所以我无法重建我的PDF文件。我通常有以下错误:“java.io.IOException:这可能不是一个PDF文件”
所以当我比较收到的数据与发送的数据,它是完全不同的。 我可以注意到,在服务器部分数据总是正确
任何帮助表示赞赏
//Server side
this.in = new ObjectInputStream(this.socket.getInputStream());
this.out = new DataOutputStream(this.socket.getOutputStream());
this.outObject = new ObjectOutputStream(this.socket.getOutputStream());
this.res = this.in.readObject().toString();//I read the client order(GET home page, next page...)
//I get the bytebuffer from the pdf file------
this.file = new File (name+this.numFile+".pdf");
RandomAccessFile raf;
raf = new RandomAccessFile(this.file, "r");
FileChannel channel = raf.getChannel();
this.buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size());
//--------------------------------------------
int size = this.buf.capacity();
this.out.writeInt(size);//I send the size of my bytebuffer to the server
int size_array = 1000;
this.pack = new byte[size_array];
this.pack = clean_array();//I replace my variable by an array filled with zeros
for(long i=0;i<(size/size_array);i++){
buf.get(this.pack);
this.out.write(this.pack);
this.pack = clean_array();//I replace my variable by an array filled with zeros
}
//I have not sent the whole bytebuffer, the last byte array could have a different size
//I work out this size, I create the new bytearray and I send it---------------------
int byteLeft = size%size_array;
if(byteLeft>0){
this.pack = new byte[byteLeft];
buf.get(this.pack);
this.out.write(this.pack);
this.pack = clean_array();//I replace my variable by an array filled with zeros
}
//-------------------------------------------------
//Client side
int size_array = 1000;
pack =new byte[size_array];
pack = clean_array();
for(int i=0;i<((size/size_array));i++){
in.read(pack);
buf.put(pack);
pack = clean_array();
}
if(size%size_array>0){
//for the last loop, the number of bytes sent by the server is not equal to 1000
//So I create a byte array with the good size
pack = new byte[size%size_array];
in.read(pack);
buf.put(pack);
pack = clean_array();
}
难道你的ObjectOutputStream和DataOutputStream在同一个基本流上有点相互冲突吗? – 2011-04-18 22:15:40
您应该使用write(byte [] b,int off,int len)写出部分字节数组。这是该方法的目的。 – Zeki 2011-04-18 22:21:43