文件传输不完全(Android)



我正在开发一个Android应用程序,通过蓝牙发送文件到java服务器,使用基于此代码片段的BlueCove库版本2.1.0。一开始一切看起来都很好,但是文件不能完全传输。35KB的只有7KB。

Android

private void sendFileViaBluetooth(byte[] data){
    OutputStream outStream = null;
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    btSocket.connect();
    try {
        outStream = btSocket.getOutputStream();
        outStream.write( data );
        outStream.write("end of file".getBytes());
        outStream.flush();
    } catch (IOException e) {
    } finally{
            try {
            outStream.close();
            btSocket.close();
            device = null;
    } catch (IOException e) {
    }
    }
}
PC服务器

InputStream inStream = connection.openInputStream();
byte[] buffer = new byte[1024];
File f = new File("d:\temp.jpg");
FileOutputStream fos = new FileOutputStream (f);
InputStream bis = new BufferedInputStream(inStream);
int bytes = 0;
boolean eof = false;
while (!eof) {
    bytes = bis.read(buffer);
    if (bytes > 0){
        int offset = bytes - 11;
        byte[] eofByte = new byte[11];
        eofByte = Arrays.copyOfRange(buffer, offset, bytes);
        String message = new String(eofByte, 0, 11);
        if(message.equals("end of file")) {
            eof = true;
        } else {
            fos.write (buffer, 0, bytes);
        }
    }
}
fos.close();
connection.close();

我已经尝试在写入之前拆分字节数组:

public static byte[][] divideArray(byte[] source, int chunksize) {
    byte[][] ret = new byte[(int)Math.ceil(source.length / (double)chunksize)][chunksize];
    int start = 0;
    for(int i = 0; i < ret.length; i++) {
        ret[i] = Arrays.copyOfRange(source,start, start + chunksize);
        start += chunksize ;
    }
    return ret;
}
private void sendFileViaBluetooth(byte[] data){
    [...]
    byte[][] chunks = divideArray(data, 1024);
    for (int i = 0; i < (int)Math.ceil(data.length / 1024.0); i += 1) {
        outStream.write( chunks[i][1024] );
    }
    outStream.write("end of file".getBytes());
    outStream.flush();
    [...]
}

感谢大家的帮助和建议

您不需要这些。Java中复制流的规范方式如下:

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}
out.close();

两端相同。TCP/IP将为您完成所有的分块处理。您所需要做的就是正确处理不同大小的读取,这段代码就是这样做的。

最新更新