Search code examples
androidbluetoothfile-transferfileinputstream

Android FileInputStream read same data continuously


I want to make bluetooth socket communication sending files

I read data by buffer from FileInputStream, and write it on other output stream.

But this program read same data continuously, not read next content.

here is my source

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

This is the log

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 

What is the problem?


Solution

  • Your code is working but what you print is not what you think it is.

    A byte array type byte[] is an Object type. If you use method toString() it will not convert bytes to String.

    If you want to convert a byte[] to a String type use : new String(my_byte_array)

    with :

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

    You'll get the right output