简体   繁体   English

Android-通过蓝牙发送文件

[英]Android - Sending file over bluetooth

I'm developing an Android application sending files from one device to another. 我正在开发一个Android应用程序,将文件从一台设备发送到另一台设备。 Establishing the connection between both devices works perfectly, but there is something going wrong while transferring the file. 在两个设备之间建立连接可以正常工作,但是在传输文件时出了点问题。 On the receiving device, the file gets created but unfortunately it's empty. 在接收设备上,文件已创建,但不幸的是它是空的。

This is my code for handling the incoming file: 这是我处理传入文件的代码:

try {
    byte[] buffer = new byte[1024];
    int bytes = 0;
    boolean eof = false;

    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "test.jpg");
    OutputStream os = null;
    try {
        os = new BufferedOutputStream(new FileOutputStream(file));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    while (!eof) {
        bytes = mmInStream.read(buffer);
        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")) {
            os.flush();
            os.close();

            eof = true;
        } else {
            os.write (buffer);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

使用DataInputStream / DataOuputStream解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM