我正在編寫一個允許從服務器下載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