【问题标题】:Android FileInputStream read same data continuouslyAndroid FileInputStream 连续读取相同的数据
【发布时间】:2015-08-16 07:45:47
【问题描述】:

我想做蓝牙socket通讯发送文件

我通过缓冲区从 FileInputStream 读取数据,并将其写入其他输出流。

但是这个程序连续读取相同的数据,而不是读取下一个内容。

这是我的来源

        MSendArgWrapper wrapper = makeWrapper(sendArg, MSendArgWrapper.MODE_SWITCH_FILE);
        try {
            byte[] bytes = CUtility.serialize(wrapper);
            outStream.write(bytes);
            outStream.flush();
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            byte buf[] = new byte[1024];
            do {
                int numread = fis.read(buf);
                if (numread <= 0)
                    break;
                if(LOG_I_ENABLE)
                    Log.i(TAG, "[CCommunicateThread] Sending File... [" + numread + "] => " + buf.toString());
                outStream.write(buf, 0, numread);
            } while (true);
            outStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            onDisconnected();
        }

这是日志

08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48
08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48
08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48
08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48
08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48
08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48
08-16 08:07:21.002 20001-21388/com.example.park.psyche I/CBluetoothManager: [CCommunicateThread] 发送文件... [1024] => [B@42b0ab48 

有什么问题?

【问题讨论】:

    标签: android bluetooth file-transfer fileinputstream


    【解决方案1】:

    您的代码正在运行,但您打印的不是您认为的那样。

    字节数组类型byte[] 是一个对象类型。如果使用toString() 方法,它不会将字节转换为字符串。

    如果要将byte[] 转换为字符串类型,请使用:new String(my_byte_array)

    与:

    Log.i(TAG, "[CCommunicateThread] Sending File... [" + numread + "] => " + new String(buf));
    

    你会得到正确的输出

    【讨论】:

    • 哦...我太愚蠢了..但是我还有另一个问题。如果我发送 7mb 文件,则需要 7 秒。如何加快蓝牙文件传输速度?
    • 我怀疑它来自您的文件读取实现。蓝牙很慢,经常遇到这个问题。如果您想检查它是否来自您的阅读实现,请将您的文件放在一个变量中并进行一些速度测试。我也不知道蓝牙套接字,但如果你有 7MB 的数据,你可以优化缓冲区大小甚至刷新频率,如本文stackoverflow.com/questions/25689871/java-file-download-hangs 中所述。这可能是有道理的,因为 Smarphone 比服务器有更多的内存/性能限制
    • 感谢您的帮助,但我认为没有办法加快蓝牙文件传输...
    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 2020-05-18
    • 2016-06-26
    • 2020-01-29
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多