0

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

安卓

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) {
    }
    }
}

电脑服务器

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

    [...]

}

感谢每一个帮助或想法。

4

1 回答 1

2

你不需要这些。在 Java 中复制流的规范方法是:

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

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

于 2013-06-16T03:27:07.920 回答