Java Code Examples for java.io.InputStream.available()

The following are Jave code examples for showing how to use available() of the java.io.InputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MultiViewAdapter   File: SimpleAdapterActivity.java   View Source Code Vote up 7 votes
private String loadJSONFromAsset() {
  String json;
  try {
    InputStream is = getAssets().open("quotes.json");
    int size = is.available();
    byte[] buffer = new byte[size];
    //noinspection ResultOfMethodCallIgnored
    is.read(buffer);
    is.close();
    json = new String(buffer, "UTF-8");
  } catch (IOException ex) {
    Log.e(TAG, "loadJSONFromAsset", ex);
    return null;
  }
  return json;
}
 
Example 2
Project: MOAAP   File: Utils.java   View Source Code Vote up 6 votes
public static Mat loadResource(Context context, int resourceId, int flags) throws IOException
{
    InputStream is = context.getResources().openRawResource(resourceId);
    ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());

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

    Mat encoded = new Mat(1, os.size(), CvType.CV_8U);
    encoded.put(0, 0, os.toByteArray());
    os.close();

    Mat decoded = Imgcodecs.imdecode(encoded, flags);
    encoded.release();

    return decoded;
}
 
Example 3
Project: MVVMFrames   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
 *
 * @param header   头部信息
 * @param filePath 本地路径
 * @return Base64编码
 */
public static String getBase64FromFile(String header, String filePath) {
    if (filePath == null || filePath.length() == 0) {
        return "File path does not exist!";
    }

    byte[] data = null;
    try {
        InputStream in = new FileInputStream(filePath);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // 对字节数组Base64编码
    return header != null ? header + Base64.encodeToString(data, Base64.DEFAULT) : Base64.encodeToString(data, Base64.DEFAULT);
}
 
Example 4
Project: hadoop-oss   File: CBZip2InputStream.java   View Source Code Vote up 6 votes
private CBZip2InputStream(final InputStream in, READ_MODE readMode, boolean skipDecompression)
    throws IOException {

  super();
  int blockSize = 0X39;// i.e 9
  this.blockSize100k = blockSize - '0';
  this.in = new BufferedInputStream(in, 1024 * 9);// >1 MB buffer
  this.readMode = readMode;
  this.skipDecompression = skipDecompression;
  if (readMode == READ_MODE.CONTINUOUS) {
    currentState = STATE.START_BLOCK_STATE;
    lazyInitialization = (in.available() == 0)?true:false;
    if(!lazyInitialization){
  init();
}
  } else if (readMode == READ_MODE.BYBLOCK) {
    this.currentState = STATE.NO_PROCESS_STATE;
    skipResult = this.skipToNextMarker(CBZip2InputStream.BLOCK_DELIMITER,DELIMITER_BIT_LENGTH);
    this.reportedBytesReadFromCompressedStream = this.bytesReadFromCompressedStream;
    if(!skipDecompression){
      changeStateToProcessABlock();
    }
  }
}
 
Example 5
Project: letv   File: IoUtils.java   View Source Code Vote up 6 votes
public static boolean copyStream(InputStream is, OutputStream os, CopyListener listener, int bufferSize) throws IOException {
    int current = 0;
    int total = is.available();
    if (total <= 0) {
        total = DEFAULT_IMAGE_TOTAL_SIZE;
    }
    byte[] bytes = new byte[bufferSize];
    if (shouldStopLoading(listener, 0, total)) {
        return false;
    }
    do {
        int count = is.read(bytes, 0, bufferSize);
        if (count != -1) {
            os.write(bytes, 0, count);
            current += count;
        } else {
            os.flush();
            return true;
        }
    } while (!shouldStopLoading(listener, current, total));
    return false;
}
 
Example 6
Project: fingerblox   File: Utils.java   View Source Code Vote up 6 votes
public static Mat loadResource(Context context, int resourceId, int flags) throws IOException
{
    InputStream is = context.getResources().openRawResource(resourceId);
    ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());

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

    Mat encoded = new Mat(1, os.size(), CvType.CV_8U);
    encoded.put(0, 0, os.toByteArray());
    os.close();

    Mat decoded = Imgcodecs.imdecode(encoded, flags);
    encoded.release();

    return decoded;
}
 
Example 7
Project: FastDFS_Client   File: StorageAppendFileCommandTest.java   View Source Code Vote up 6 votes
/**
 * 文件续传需要先使用 append模式Save一个可以续传的文件
 * 然后才能使用续传命令续传文件
 * 
 * @throws IOException
 */
@Test
public void testStorageAppendFileCommand() throws IOException {
    String firstText = "Tobato is a good man.他是一个好人\r\n";
    InputStream firstIn = getTextInputStream(firstText);
    long firstSize = firstIn.available();
    // 先上载第一段文字
    StorePath path = uploadInputStream(firstIn, "txt", firstSize, true);
    // 添加第二段文字
    String secendText = "Work hard and hard. 努力工作啊\r\n";
    InputStream secendIn = getTextInputStream(secendText);
    long secendSize = secendIn.available();
    // 文件续传
    execStorageAppendFileCommand(secendIn, secendSize, path.getPath());
    firstIn.close();
    secendIn.close();
}
 
Example 8
Project: Android-Code-Demos   File: Utils.java   View Source Code Vote up 6 votes
public static Mat loadResource(Context context, int resourceId, int flags) throws IOException
{
    InputStream is = context.getResources().openRawResource(resourceId);
    ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());

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

    Mat encoded = new Mat(1, os.size(), CvType.CV_8U);
    encoded.put(0, 0, os.toByteArray());
    os.close();

    Mat decoded = Imgcodecs.imdecode(encoded, flags);
    encoded.release();

    return decoded;
}
 
Example 9
Project: ImageLoaderSupportGif   File: IoUtils.java   View Source Code Vote up 6 votes
/**
 * Copies stream, fires progress events by listener, can be interrupted by listener.
 *
 * @param is         Input stream
 * @param os         Output stream
 * @param listener   null-ok; Listener of copying progress and controller of copying interrupting
 * @param bufferSize Buffer size for copying, also represents a step for firing progress listener callback, i.e.
 *                   progress event will be fired after every copied <b>bufferSize</b> bytes
 * @return <b>true</b> - if stream copied successfully; <b>false</b> - if copying was interrupted by listener
 * @throws IOException
 */
public static boolean copyStream(InputStream is, OutputStream os, CopyListener listener, int bufferSize)
		throws IOException {
	int current = 0;
	int total = is.available();
	if (total <= 0) {
		total = DEFAULT_IMAGE_TOTAL_SIZE;
	}

	final byte[] bytes = new byte[bufferSize];
	int count;
	if (shouldStopLoading(listener, current, total)) return false;
	while ((count = is.read(bytes, 0, bufferSize)) != -1) {
		os.write(bytes, 0, count);
		current += count;
		if (shouldStopLoading(listener, current, total)) return false;
	}
	os.flush();
	return true;
}
 
Example 10
Project: fuck_zookeeper   File: StaticContent.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
String path = request.getRequestURI().substring(request.getServletPath().length());

InputStream resource = ClassLoader.getSystemResourceAsStream("org/apache/zookeeper/graph/resources" + path);	  
if (resource == null) {
    response.getWriter().println(path + " not found!");
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    return;
}
try {
  while (resource.available() > 0) {
    response.getWriter().write(resource.read());
  }
} finally {
  resource.close();
}
//        response.setContentType("text/plain;charset=utf-8");
       response.setStatus(HttpServletResponse.SC_OK);
   }
 
Example 11
Project: openjdk-jdk10   File: MicToken.java   View Source Code Vote up 5 votes
public MicToken(Krb5Context context, MessageProp prop,
                InputStream data)
      throws GSSException, IOException {
      super(Krb5Token.MIC_ID, context);
      byte[] dataBytes = new byte[data.available()];
      data.read(dataBytes);

      //debug("Application data to MicToken cons is [" +
      //     getHexBytes(dataBytes) + "]\n");
      if (prop == null) prop = new MessageProp(0, false);
      genSignAndSeqNumber(prop, null, dataBytes, 0, dataBytes.length, null);
}
 
Example 12
Project: ConcealSharedPreference-Android   File: Data.java   View Source Code Vote up 5 votes
public static String loadJSONFromAsset(Context context, String filename) {
    String json = null;
    try {
        InputStream is = context.getAssets().open(filename);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
 
Example 13
Project: Mastering-Java-EE-Development-with-WildFly   File: ClientFirstReaderInterceptor.java   View Source Code Vote up 5 votes
@Override
public Object aroundReadFrom(ReaderInterceptorContext interceptorContext)
		throws IOException, WebApplicationException {
	logger.info("ClientFirstReaderInterceptor invoked");
	InputStream inputStream = interceptorContext.getInputStream();
	byte[] bytes = new byte[inputStream.available()];
	inputStream.read(bytes);
	String requestContent = new String(bytes);
	requestContent = requestContent + ".Request changed in ClientFirstReaderInterceptor.";
	interceptorContext.setInputStream(new ByteArrayInputStream(requestContent.getBytes()));
	return interceptorContext.proceed();
}
 
Example 14
Project: dubbocloud   File: DubboCodec.java   View Source Code Vote up 5 votes
private byte[] readMessageData(InputStream is) throws IOException {
    if (is.available() > 0) {
        byte[] result = new byte[is.available()];
        is.read(result);
        return result;
    }
    return new byte[]{};
}
 
Example 15
Project: openjdk-jdk10   File: CustomLoader.java   View Source Code Vote up 5 votes
private byte[] locateBytes() throws IOException {
    try {
        JarFile jar = new JarFile("Agent.jar");
        InputStream is = jar.getInputStream(jar.getEntry("Agent.class"));
        int len = is.available();
        byte[] buf = new byte[len];
        DataInputStream in = new DataInputStream(is);
        in.readFully(buf);
        return buf;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new IOException("Test failed due to IOException!");
    }
}
 
Example 16
Project: MakiLite   File: StandartMessages.java   View Source Code Vote up 5 votes
private void injectMaterialCSS(String mode) {
	try {
		InputStream inputStream = getAssets().open("makitheme.css");
		byte[] buffer = new byte[inputStream.available()];
		inputStream.read(buffer);
		inputStream.close();
		webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()");
	} catch (Exception fb) {
		fb.printStackTrace();
	}
}
 
Example 17
Project: incubator-netbeans   File: JarFileSystem.java   View Source Code Vote up 5 votes
private InputStream getMemInputStream(JarFile jf, JarEntry je)
throws IOException {
    InputStream is = getInputStream4336753(jf, je);
    ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());

    try {
        FileUtil.copy(is, os);
    } finally {
        os.close();
    }

    return new ByteArrayInputStream(os.toByteArray());
}
 
Example 18
Project: CustomAndroidOneSheeld   File: OneSheeldApplication.java   View Source Code Vote up 5 votes
public String loadData(String inFile) throws IOException {
    String tContents = "";
    InputStream stream = getAssets().open(inFile);
    int size = stream.available();
    byte[] buffer = new byte[size];
    stream.read(buffer);
    stream.close();
    tContents = new String(buffer);
    return tContents;
}
 
Example 19
Project: lams   File: AbstractVerifier.java   View Source Code Vote up 4 votes
public final void verify(String host, SSLSocket ssl)
      throws IOException {
    if(host == null) {
        throw new NullPointerException("host to verify is null");
    }

    SSLSession session = ssl.getSession();
    if(session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        InputStream in = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:

            #1.  Clean up the certificate chain that your server
                 is presenting (e.g. edit "/etc/apache2/server.crt"
                 or wherever it is your server's certificate chain
                 is defined).

                                       OR

            #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                  to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if(session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    Certificate[] certs = session.getPeerCertificates();
    X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}
 
Example 20
Project: dubbo2   File: StreamUtils.java   View Source Code Vote up 4 votes
public static void skipUnusedStream(InputStream is) throws IOException {
    if (is.available() > 0) {
        is.skip(is.available());
    }
}