ok,你这个错误在于: DataInputStream input = new DataInputStream(socket.getInputStream()); input.read(portReturnData, 0, 1024); 并不能保证一次会读1024个字节,这个1024是指这一次从网络流所读的最大字节数, 一般程序是这样做的 int rcv=0,temp=0; while((temp=input.read(portReturnData,rcv,1024-rcv))>0) { rcv+=temp; } 即需要多次调用流的read方法才能把数据收全。u can try.
试一试这个write()方法: public void write(byte[] b, int off, int len) throws IOException Writes len bytes from the specified byte array starting at offset off to the underlying output stream. If no exception is thrown, the counter written is incremented by len.
public byte[] copyStreamToByteArray(InputStream input){ try{ int index = 0; int len = input.available(); byte[] bys = new byte[len+1]; byte[] temp = null; int next = 0; int off = 0; int save = len; while(true){ while (off <= len){ //这个while 而不用if 就是input.read 的时候 "并不能保证一次会读len个字节" 即zone2000(猪宝宝)言. index = input.read(bys, off, len-off+1); if(index <= 0) break; off += index;
} next = input.available(); //苹果机 的input.available (好像不是文件的大小) 有点不一样我才这样多取几次的. if(next > 0){ temp = new byte[len + 1 + next]; for(int i=0; i<=len; i++){ temp[i] = bys[i]; } bys = temp; off = len + 1; len = len + next + 1; }else{ break; } } input.close(); }catch (IOException ex) { ex.printStackTrace(); }
DataInputStream input = new DataInputStream(socket.getInputStream());
input.read(portReturnData, 0, 1024);
并不能保证一次会读1024个字节,这个1024是指这一次从网络流所读的最大字节数,
一般程序是这样做的
int rcv=0,temp=0;
while((temp=input.read(portReturnData,rcv,1024-rcv))>0)
{
rcv+=temp;
}
即需要多次调用流的read方法才能把数据收全。u can try.
public void write(byte[] b,
int off,
int len)
throws IOException
Writes len bytes from the specified byte array starting at offset off to the underlying output stream. If no exception is thrown, the counter written is incremented by len.
try{
int index = 0;
int len = input.available();
byte[] bys = new byte[len+1];
byte[] temp = null;
int next = 0;
int off = 0;
int save = len;
while(true){
while (off <= len){ //这个while 而不用if 就是input.read 的时候 "并不能保证一次会读len个字节" 即zone2000(猪宝宝)言.
index = input.read(bys, off, len-off+1);
if(index <= 0)
break;
off += index;
}
next = input.available(); //苹果机 的input.available (好像不是文件的大小) 有点不一样我才这样多取几次的.
if(next > 0){
temp = new byte[len + 1 + next];
for(int i=0; i<=len; i++){
temp[i] = bys[i];
}
bys = temp;
off = len + 1;
len = len + next + 1;
}else{
break;
}
}
input.close();
}catch (IOException ex) {
ex.printStackTrace();
}
while(true){
}
while(true){
}