Android FileInputStream 连续读取相同的数据

Android FileInputStream read same data continuously

我想做蓝牙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] Sending File... [1024] => [B@42b0ab48
08-16 08:07:21.002  20001-21388/com.example.park.psyche I/CBluetoothManager﹕ [CCommunicateThread] Sending File... [1024] => [B@42b0ab48
08-16 08:07:21.002  20001-21388/com.example.park.psyche I/CBluetoothManager﹕ [CCommunicateThread] Sending File... [1024] => [B@42b0ab48
08-16 08:07:21.002  20001-21388/com.example.park.psyche I/CBluetoothManager﹕ [CCommunicateThread] Sending File... [1024] => [B@42b0ab48
08-16 08:07:21.002  20001-21388/com.example.park.psyche I/CBluetoothManager﹕ [CCommunicateThread] Sending File... [1024] => [B@42b0ab48
08-16 08:07:21.002  20001-21388/com.example.park.psyche I/CBluetoothManager﹕ [CCommunicateThread] Sending File... [1024] => [B@42b0ab48
08-16 08:07:21.002  20001-21388/com.example.park.psyche I/CBluetoothManager﹕ [CCommunicateThread] Sending File... [1024] => [B@42b0ab48 

有什么问题?

您的代码可以正常工作,但您打印的内容与您想象的不同。

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

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

与:

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

你会得到正确的输出