java nio如何接收c++发过来的图片?socket我就知道

2025-05-07 23:25:30
推荐回答(1个)
回答1:

用SocketChanne从socket里读文件数据流,

用NIO的FileChannel从ByteBuffer里读缓存数据写入FileOutputStream:

    private static void receiveFile(SocketChannel socketChannel, File file) throws IOException {  
        FileOutputStream fos = null;  
        FileChannel channel = null;  
          
        try {  
            fos = new FileOutputStream(file);  
            channel = fos.getChannel();  
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);  
  
            int size = 0;  
            while ((size = socketChannel.read(buffer)) != -1) {  
                buffer.flip();  
                if (size > 0) {  
                    buffer.limit(size);  
                    channel.write(buffer);  
                    buffer.clear();  
                }  
            }  
        } finally {  
            try {  
                channel.close();  
            } catch(Exception ex) {}  
            try {  
                fos.close();  
            } catch(Exception ex) {}  
        }  
    }