java.io.InputStream#read ( )源码实例Demo

下面列出了java.io.InputStream#read ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: tilt-game-android   文件: StreamUtils.java
/**
 * @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 + "'.");
	}
}
 
源代码2 项目: wandora   文件: StaticContentAction.java
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;
}
 
源代码3 项目: jdk8u-jdk   文件: bug8062561.java
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;
}
 
源代码4 项目: MOAAP   文件: Utils.java
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);
    }
}
 
源代码5 项目: localify   文件: LocalifyModule.java
@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 "";
}
 
源代码6 项目: spork   文件: JarManager.java
/**
 * 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);
    }
}
 
/**
 * 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;
}
 
源代码8 项目: PixelFlow   文件: SMAA.java
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);
}
 
源代码9 项目: FxDock   文件: CKit.java
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;
	}
}
 
源代码10 项目: device-database   文件: BasicNetwork.java
/** 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();
    }
}
 
源代码11 项目: strimzi-kafka-operator   文件: MockCertManager.java
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();
}
 
源代码12 项目: jdk8u60   文件: Source.java
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();
    }
}
 
源代码13 项目: oxTrust   文件: ServiceUtil.java
/**
 * 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);
	}
}
 
源代码14 项目: openjdk-jdk8u-backup   文件: HttpClientTransport.java
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();
            }
        }
    };
}
 
源代码15 项目: JFX-Browser   文件: Client.java
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);
	}
}
 
源代码16 项目: mimi-reader   文件: IOUtils.java
/**
 * 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;
}
 
源代码17 项目: jdk8u_jdk   文件: SSLSocketTemplate.java
protected void runClientApplication(SSLSocket socket) throws Exception {
    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslOS.write(280);
    sslOS.flush();
    sslIS.read();
}
 
源代码18 项目: openjdk-jdk9   文件: GZIPInputStream.java
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;
}
 
源代码19 项目: saros   文件: Socks5StreamService.java
/**
 * 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;
}
 
源代码20 项目: tcc-transaction   文件: StaticContentServlet.java
@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();
    }
}