尝试从套接字转换流时,为什么会出现ClassCastException?

时间:2013-12-09 18:50:00

标签: android classcastexception outputstream dataoutputstream

我正在尝试在我的Android应用程序(客户端)和我的python服务器之间建立蓝牙连接。但是,我遇到了流的问题。这段代码抛出一个ClassCastException,我不知道为什么以及如何修复它。任何想法或提示?

public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            // THIS IS WHERE THE EXCEPTION IS THROWN
            tmpIn = (DataInputStream) socket.getInputStream(); 
            tmpOut = (DataOutputStream) socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

1 个答案:

答案 0 :(得分:0)

Socket.getInputStream()返回一个InputStream,而不是DataInputStream。 Socket.getOutputStream()返回一个OutputStream,而不是DataOutputStream。 除非您100%确定类型,否则不应将InputStream或OutputStream强制转换为子类。但是,您可以从原始InputStreams和OutputStreams创建DataInputStream或DataOutputStream(参见下文)。

您可以删除强制转换以使您的代码看起来像这样(如果mmInStream和mmOutStream变量是这样的话,您还需要创建一个新的DataInputStream和新的DataOutputStream):

public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the BluetoothSocket input and output streams
    try {
        tmpIn = socket.getInputStream(); 
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, "temp sockets not created", e);
    }
    mmInStream = new DataInputStream(tmpIn);
    mmOutStream = new DataOutputStream(tmpOut);
}

(PS。别忘了关闭你的溪流!)