Here you can find the source of readDelimitedFromInputStream(InputStream inputStream)
Parameter | Description |
---|---|
inputStream | the input stream to read from |
Parameter | Description |
---|---|
IOException | if a problem occurs |
protected static byte[] readDelimitedFromInputStream(InputStream inputStream) throws IOException
//package com.java2s; /*/*from w w w .ja v a2 s.c om*/ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; public class Main { /** * Read length delimited data from the input stream * * @param inputStream the input stream to read from * @return the bytes read * @throws IOException if a problem occurs */ protected static byte[] readDelimitedFromInputStream(InputStream inputStream) throws IOException { byte[] sizeBytes = new byte[4]; int numRead = inputStream.read(sizeBytes, 0, 4); if (numRead < 4) { throw new IOException("Failed to read the message size from the input stream!"); } int messageLength = ByteBuffer.wrap(sizeBytes).getInt(); byte[] messageData = new byte[messageLength]; // for (numRead = 0; numRead < messageLength; numRead += // inputStream.read(messageData, numRead, messageLength - numRead)); for (numRead = 0; numRead < messageLength;) { int currentNumRead = inputStream.read(messageData, numRead, messageLength - numRead); if (currentNumRead < 0) { throw new IOException("Unexpected end of stream!"); } numRead += currentNumRead; } return messageData; } }