Java Code Examples for java.io.InputStream#read()

The following examples show how to use java.io.InputStream#read() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tilt-game-android   File: StreamUtils.java    License: MIT License 6 votes vote down vote up
/**
 * @param pInputStream the sources of the bytes.
 * @param pByteLimit the amount of bytes to read.
 * @param pData the array to place the read bytes in.
 * @param pOffset the offset within pData.
 * @throws IOException
 */
public static final void streamToBytes(final InputStream pInputStream, final int pByteLimit, final byte[] pData, final int pOffset) throws IOException {
	if (pByteLimit > pData.length - pOffset) {
		throw new IOException("pData is not big enough.");
	}

	int pBytesLeftToRead = pByteLimit;
	int readTotal = 0;
	int read;
	while ((read = pInputStream.read(pData, pOffset + readTotal, pBytesLeftToRead)) != StreamUtils.END_OF_STREAM) {
		readTotal += read;
		if (pBytesLeftToRead > read) {
			pBytesLeftToRead -= read;
		} else {
			break;
		}
	}

	if (readTotal != pByteLimit) {
		throw new IOException("ReadLimit: '" + pByteLimit + "', Read: '" + readTotal + "'.");
	}
}
 
Example 2
protected boolean returnFile(HttpServletResponse response,File f) throws IOException {
    if(!f.exists() || f.isDirectory()){
        return false;
    }

    Object o=mimeTypes.getMimeByExtension(f.getName());
    if(o!=null) response.setContentType(o.toString());
    else response.setContentType("text/plain");
    OutputStream out=response.getOutputStream();

    InputStream in=new FileInputStream(f);
    byte[] buf=new byte[8192];
    int read=-1;
    while((read=in.read(buf))!=-1){
        out.write(buf,0,read);
    }
    out.flush();
    in.close();
    
    return true;
}
 
Example 3
public static boolean dumpStream(InputStream in) throws IOException {
    String tempString;
    int count = in.available();
    boolean exception = false;
    while (count > 0) {
        byte[] b = new byte[count];
        in.read(b);
        tempString = new String(b);
        if (!exception) {
            exception = tempString.indexOf("Exception") != -1;
        }
        System.out.println(tempString);
        count = in.available();
    }

    return exception;
}
 
Example 4
Source Project: MOAAP   File: Utils.java    License: MIT License 6 votes vote down vote up
public static String exportResource(Context context, int resourceId, String dirname) {
    String fullname = context.getResources().getString(resourceId);
    String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
    try {
        InputStream is = context.getResources().openRawResource(resourceId);
        File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
        File resFile = new File(resDir, resName);

        FileOutputStream os = new FileOutputStream(resFile);

        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        is.close();
        os.close();

        return resFile.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CvException("Failed to export resource " + resName
                + ". Exception thrown: " + e);
    }
}
 
Example 5
Source Project: localify   File: LocalifyModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String loadAssetsFile(String fileName) {
    if(assetManager == null) {
        throw new IllegalStateException("First you have to init the Asset Manager");
    }

    int size = 0;
    byte[] buffer = null;
    try {
        InputStream is = assetManager.open(fileName);
        size = is.available();
        buffer = new byte[size];
        is.read(buffer);
        is.close();

        return new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}
 
Example 6
Source Project: spork   File: JarManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds a stream to a Jar file.
 *
 * @param os
 *            the OutputStream of the Jar file to which the stream will be added.
 * @param name
 *            the name of the stream.
 * @param is
 *            the stream to add.
 * @param contents
 *            the current contents of the Jar file. (We use this to avoid adding two streams
 *            with the same name.
 * @param timestamp
 *            timestamp of the entry
 * @throws IOException
 */
private static void addStream(JarOutputStream os, String name, InputStream is, Map<String, String> contents,
        long timestamp)
        throws IOException {
    if (contents.get(name) != null) {
        return;
    }
    contents.put(name, "");
    JarEntry entry = new JarEntry(name);
    entry.setTime(timestamp);
    os.putNextEntry(entry);
    byte buffer[] = new byte[4096];
    int rc;
    while ((rc = is.read(buffer)) > 0) {
        os.write(buffer, 0, rc);
    }
}
 
Example 7
/**
 * Write the contents of an input stream into a byte array.
 * @param inputStream The stream to convert into a byte array.
 * @return A byte array containing the contents of the input stream.
 * @throws IOException
 */
private static byte[] convertInputStreamToByteArray(InputStream inputStream) throws IOException {
  byte[] bytes = null;
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte data[] = new byte[1024];
  int count;
  while ((count = inputStream.read(data)) != -1) {
    bos.write(data, 0, count);
  }
  bos.flush();
  bos.close();
  inputStream.close();
  bytes = bos.toByteArray();
  return bytes;
}
 
Example 8
Source Project: PixelFlow   File: SMAA.java    License: MIT License 5 votes vote down vote up
private ByteBuffer readTexData(String path, byte[] data){
  InputStream is = new DwUtils(context).createInputStream(path);
  try {
    is.read(data);
    is.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return ByteBuffer.wrap(data);
}
 
Example 9
Source Project: FxDock   File: CKit.java    License: Apache License 2.0 5 votes vote down vote up
public static void readFully(InputStream in, byte b[]) throws Exception
{
	int offset = 0;
	while(offset < b.length)
	{
		int count = in.read(b, offset, b.length - offset);
		if(count < 0)
		{
			throw new EOFException("read only " + offset + " bytes instead of " + b.length);
		}
		offset += count;
	}
}
 
Example 10
Source Project: device-database   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 11
private static byte[] loadResource(InputStream is) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {
        int read;
        byte[] data = new byte[2048];
        while ((read = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, read);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return buffer.toByteArray();
}
 
Example 12
Source Project: jdk8u60   File: Source.java    License: GNU General Public License v2.0 5 votes vote down vote up
static byte[] readBytes(final InputStream is) throws IOException {
    final byte[] arr = new byte[BUF_SIZE];
    try {
        try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) {
            int numBytes;
            while ((numBytes = is.read(arr, 0, arr.length)) > 0) {
                buf.write(arr, 0, numBytes);
            }
            return buf.toByteArray();
        }
    } finally {
        is.close();
    }
}
 
Example 13
Source Project: oxTrust   File: ServiceUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Read all bytes from the supplied input stream. Closes the input stream.
 *
 * @param is
 *            Input stream
 * @return All bytes
 * @throws IOException
 *             If an I/O problem occurs
 */
public static byte[] readFully(InputStream is) throws IOException {
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){
		byte[] buffer = new byte[2048];
		int read = 0;
		while ((read = is.read(buffer)) != -1) {
			baos.write(buffer, 0, read);
		}
		return baos.toByteArray();
	} finally {
		IOUtils.closeQuietly(is);
	}
}
 
Example 14
protected @Nullable InputStream readResponse() {
    InputStream is;
    try {
        is = httpConnection.getInputStream();
    } catch(IOException ioe) {
        is = httpConnection.getErrorStream();
    }
    if (is == null) {
        return is;
    }
    // Since StreamMessage doesn't read </s:Body></s:Envelope>, there
    // are some bytes left in the InputStream. This confuses JDK and may
    // not reuse underlying sockets. Hopefully JDK fixes it in its code !
    final InputStream temp = is;
    return new FilterInputStream(temp) {
        // Workaround for "SJSXP XMLStreamReader.next() closes stream".
        // So it doesn't read from the closed stream
        boolean closed;
        @Override
        public void close() throws IOException {
            if (!closed) {
                closed = true;
                while(temp.read(THROW_AWAY_BUFFER) != -1);
                super.close();
            }
        }
    };
}
 
Example 15
Source Project: JFX-Browser   File: Client.java    License: MIT License 5 votes vote down vote up
private static void copyStream(InputStream in, OutputStream out) throws IOException {
	byte[] buffer = new byte[8192];
	while (true) {
		int bytesRead = in.read(buffer, 0, 8192);
		if (bytesRead == -1) break;
		out.write(buffer, 0, bytesRead);
	}
}
 
Example 16
Source Project: mimi-reader   File: IOUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Simple wrapper around {@link java.io.InputStream#read()} that throws EOFException
 * instead of returning -1.
 */
public static int read(InputStream is) throws IOException {
    int b = is.read();
    if (b == -1) {
        throw new EOFException();
    }
    return b;
}
 
Example 17
protected void runClientApplication(SSLSocket socket) throws Exception {
    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslOS.write(280);
    sslOS.flush();
    sslIS.read();
}
 
Example 18
private int readUByte(InputStream in) throws IOException {
    int b = in.read();
    if (b == -1) {
        throw new EOFException();
    }
    if (b < -1 || b > 255) {
        // Report on this.in, not argument in; see read{Header, Trailer}.
        throw new IOException(this.in.getClass().getName()
            + ".read() returned value out of range -1..255: " + b);
    }
    return b;
}
 
Example 19
/**
 * Sends and receives an INT to distinguish between bidirectional and unidirectional streams.
 *
 * @param session
 * @param sendFirst
 * @return whether a stream is bidirectional
 * @throws IOException
 */
private boolean streamIsBidirectional(Socks5BytestreamSession session, boolean sendFirst)
    throws IOException {

  try {
    OutputStream out = session.getOutputStream();
    InputStream in = session.getInputStream();
    int test = 0;

    session.setReadTimeout(MEDIATED_BIDIRECTIONAL_TEST_TIMEOUT);

    if (sendFirst) {
      out.write(BIDIRECTIONAL_TEST_BYTE);
      test = in.read();
    } else {
      test = in.read();
      out.write(BIDIRECTIONAL_TEST_BYTE);
    }

    if (test == BIDIRECTIONAL_TEST_BYTE) {
      log.trace(
          prefix() + "stream is bidirectional. (" + (sendFirst ? "sending" : "receiving") + ")");
      return true;
    } else {
      log.error(prefix() + "stream can send and receive but got wrong result: " + test);
      throw new IOException("SOCKS5 bytestream connections got mixed up. Try another transport.");
      /*
       * Note: a reason here might be a too low TEST_TIMEOUT but the
       * exception enables fallback to IBB instead of having the
       * stream crash on first use.
       */
    }

  } catch (SocketTimeoutException ste) {
    /*
     * At least we have to wait TEST_STREAM_TIMEOUT to cause a timeout
     * on the peer side, too.
     *
     * Else the first package might be read and the above error occurs
     * (test != BIDIRECTIONAL_TEST_BYTE).
     */
    try {
      Thread.sleep(MEDIATED_BIDIRECTIONAL_TEST_TIMEOUT);
    } catch (InterruptedException e) {
      // nothing to do here
    }
  }

  /*
   * Note: the streams cannot be closed here - even not the unused ones -
   * as setting the timeout later on would throw an exception
   */

  log.debug(prefix() + "stream is unidirectional. Trying to wrap bidirectional one.");

  return false;
}
 
Example 20
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getRequestURI();
    if(path.equals("/")){
        path = "/index.html";
    }
    String ext = path.substring(path.lastIndexOf(".")+1);
    String mediaType = EXT_TO_MEDIATYPE.get(ext);
    byte[] contentBytes = null;

    if(mediaType!=null){
        contentBytes = CONTENT_CACHE.get(path);
        if (contentBytes == null) {
            InputStream is = getClass().getClassLoader().getResourceAsStream("message.content" + path);
            if (is != null) {
                try {
                    ByteArrayOutputStream os = new ByteArrayOutputStream(4096);
                    byte[] bs = new byte[4096];
                    int c = 0;
                    while((c = is.read(bs)) > 0){
                        os.write(bs,0,c);
                    }
                    contentBytes=os.toByteArray();
                    CONTENT_CACHE.putIfAbsent(path, contentBytes);
                } catch (IOException e) {
                    try {
                        is.close();
                    } catch (IOException e1) {
                        log.warn("Could not close the resource " + path, e1);
                    }
                }
            }

        }
    }

    if (contentBytes == null) {
        resp.sendError(Response.SC_NOT_FOUND);
    }else {
    	resp.setCharacterEncoding("utf-8");
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Headers","Content-Type, Accept");
        resp.setContentType(mediaType);
        resp.setStatus(Response.SC_OK);
        resp.getOutputStream().write(contentBytes);
        resp.getOutputStream().close();
    }
}