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

The following are Jave code examples for showing how to use read() 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: FreeStreams-TVLauncher   File: FileUtils.java   View Source Code Vote up 6 votes
public static void copyFile(String oldPathFile, String newPathFile) {
	try {
		int bytesum = 0;
		int byteread = 0;
		File oldfile = new File(oldPathFile);
		if (oldfile.exists()) { // 文件存在
			InputStream inStream = new FileInputStream(oldPathFile); // 读入源文�?
			File n = new File(newPathFile);
			if (!n.exists()) {
				n.createNewFile();
			}
			FileOutputStream fs = new FileOutputStream(newPathFile);
			byte[] buffer = new byte[1444];
			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread; // 字节 文件大小
				fs.write(buffer, 0, byteread);
			}
			fs.flush();
			fs.close();
			inStream.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Project: Android-UtilCode   File: ConvertUtils.java   View Source Code Vote up 6 votes
/**
 * inputStream转outputStream
 *
 * @param is 输入流
 * @return outputStream子类
 */
public static ByteArrayOutputStream input2OutputStream(InputStream is) {
    if (is == null) return null;
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] b = new byte[MemoryConstants.KB];
        int len;
        while ((len = is.read(b, 0, MemoryConstants.KB)) != -1) {
            os.write(b, 0, len);
        }
        return os;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(is);
    }
}
 
Example 3
Project: AndroidProgramming3e   File: FlickrFetchr.java   View Source Code Vote up 6 votes
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 4
Project: MakiLite   File: StandartMessages.java   View Source Code Vote up 5 votes
private void injectDraculaCSS(String mode) {
	try {
		InputStream inputStream = getAssets().open("dracula.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 d) {
		d.printStackTrace();
	}
}
 
Example 5
Project: keepass2android   File: Streams.java   View Source Code Vote up 5 votes
public static void drain(InputStream inStr)
    throws IOException
{
    byte[] bs = new byte[BUFFER_SIZE];
    while (inStr.read(bs, 0, bs.length) >= 0)
    {
    }
}
 
Example 6
Project: Codeforces   File: DiskBasedCache.java   View Source Code Vote up 5 votes
/**
 * Simple wrapper around {@link InputStream#read()} that throws EOFException
 * instead of returning -1.
 */
private static int read(InputStream is) throws IOException {
    int b = is.read();
    if (b == -1) {
        throw new EOFException();
    }
    return b;
}
 
Example 7
Project: ipack   File: DHIESPublicKeyParser.java   View Source Code Vote up 5 votes
public AsymmetricKeyParameter readKey(InputStream stream)
    throws IOException
{
    byte[] V = new byte[(dhParams.getP().bitLength() + 7) / 8];

    stream.read(V, 0, V.length);

    return new DHPublicKeyParameters(new BigInteger(1, V), dhParams);
}
 
Example 8
Project: light-session-4j   File: HttpClientUtils.java   View Source Code Vote up 5 votes
public static String readResponse(InputStream stream) throws IOException {

        byte[] data = new byte[100];
        int read;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((read = stream.read(data)) != -1) {
            out.write(data, 0, read);
        }
        return new String(out.toByteArray(), StandardCharsets.UTF_8);
    }
 
Example 9
Project: OpenJSharp   File: AcceptSecContextToken.java   View Source Code Vote up 5 votes
/**
 * Creates an AcceptSecContextToken at the context initiator's side
 * using the bytes received from  the acceptor.
 */
public AcceptSecContextToken(Krb5Context context,
                             Credentials serviceCreds, KrbApReq apReq,
                             InputStream is)
    throws IOException, GSSException, KrbException  {

    int tokenId = ((is.read()<<8) | is.read());

    if (tokenId != Krb5Token.AP_REP_ID)
        throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                               "AP_REP token id does not match!");

    byte[] apRepBytes =
        new sun.security.util.DerValue(is).toByteArray();

    KrbApRep apRep = new KrbApRep(apRepBytes, serviceCreds, apReq);

    /*
     * Allow the context acceptor to set a subkey if desired, even
     * though our context acceptor will not do so.
     */
    EncryptionKey subKey = apRep.getSubKey();
    if (subKey != null) {
        context.setKey(Krb5Context.ACCEPTOR_SUBKEY, subKey);
        /*
        System.out.println("\n\nSub-Session key from AP-REP is: " +
                           getHexBytes(subKey.getBytes()) + "\n");
        */
    }

    Integer apRepSeqNumber = apRep.getSeqNumber();
    int peerSeqNumber = (apRepSeqNumber != null ?
                         apRepSeqNumber.intValue() :
                         0);
    context.resetPeerSequenceNumber(peerSeqNumber);
}
 
Example 10
Project: MakiLite   File: MainActivity.java   View Source Code Vote up 5 votes
private void injectHide(String mode) {
    try {
        InputStream inputStream = getAssets().open("hidepeople.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 d) {
        d.printStackTrace();
    }
}
 
Example 11
Project: openjdk-jdk10   File: ShellFolderMemoryLeak.java   View Source Code Vote up 5 votes
public static boolean checkExceptions(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.contains("RunTimeException");
        }
        count = in.available();
    }
    return exception;
}
 
Example 12
Project: automat   File: ProtoCommon.java   View Source Code Vote up 5 votes
/**
* receive whole pack
* @param in input stream
* @param expect_cmd expect response command
* @param expect_body_len expect response package body length
* @return PkgInfo: status and reponse body(byte buff)
*/
	public static PkgInfo recvPackage(InputStream in, byte expect_cmd, long expect_body_len) throws IOException
	{
		PkgHeader header = recvHeader(in, expect_cmd, expect_body_len);
		if (header.status != 0)
		{
			return new PkgInfo(header, null);
		}
		
		byte[] body = new byte[header.body_len];
		int totalBytes = 0;
		int remainBytes = header.body_len;
		int bytes;
		
		while (totalBytes < header.body_len)
		{
			if ((bytes=in.read(body, totalBytes, remainBytes)) < 0)
			{
				break;
			}
			
			totalBytes += bytes;
			remainBytes -= bytes;
		}
		
		if (totalBytes != header.body_len)
		{
			throw new IOException("recv package size " + totalBytes + " != " + header.body_len);
		}
		
		return new PkgInfo(header, body);
	}
 
Example 13
Project: airgram   File: DiskBasedCache.java   View Source Code Vote up 5 votes
/**
 * Simple wrapper around {@link InputStream#read()} that throws EOFException
 * instead of returning -1.
 */
private static int read(InputStream is) throws IOException {
    int b = is.read();
    if (b == -1) {
        throw new EOFException();
    }
    return b;
}
 
Example 14
Project: openjdk-jdk10   File: CookieHttpsClientTest.java   View Source Code Vote up 5 votes
static void readOneRequest(InputStream is) throws IOException {
    int requestEndCount = 0, r;
    while ((r = is.read()) != -1) {
        if (r == requestEnd[requestEndCount]) {
            requestEndCount++;
            if (requestEndCount == 4) {
                break;
            }
        } else {
            requestEndCount = 0;
        }
    }
}
 
Example 15
Project: alerta-fraude   File: LocalFilesystem.java   View Source Code Vote up 5 votes
private static void copyResource(CordovaResourceApi.OpenForReadResult input, OutputStream outputStream) throws IOException {
    try {
        InputStream inputStream = input.inputStream;
        if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
            FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
            FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
            long offset = 0;
            long length = input.length;
            if (input.assetFd != null) {
                offset = input.assetFd.getStartOffset();
            }
            // transferFrom()'s 2nd arg is a relative position. Need to set the absolute
            // position first.
            inChannel.position(offset);
            outChannel.transferFrom(inChannel, 0, length);
        } else {
            final int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            for (;;) {
                int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);

                if (bytesRead <= 0) {
                    break;
                }
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    } finally {
        input.inputStream.close();
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
 
Example 16
Project: ramus   File: DataLoader.java   View Source Code Vote up 5 votes
public static double readDouble(final InputStream stream)
        throws IOException {
    long res = stream.read();
    res |= (long) stream.read() << 8;
    res |= (long) stream.read() << 16;
    res |= (long) stream.read() << 24;
    res |= (long) stream.read() << 32;
    res |= (long) stream.read() << 40;
    res |= (long) stream.read() << 48;
    res |= (long) stream.read() << 56;
    return Double.longBitsToDouble(res);
}
 
Example 17
Project: OpenJSharp   File: AiffFileWriter.java   View Source Code Vote up 5 votes
private int writeAiffFile(InputStream in, AiffFileFormat aiffFileFormat, OutputStream out) throws IOException {

        int bytesRead = 0;
        int bytesWritten = 0;
        InputStream fileStream = getFileStream(aiffFileFormat, in);
        byte buffer[] = new byte[bisBufferSize];
        int maxLength = aiffFileFormat.getByteLength();

        while( (bytesRead = fileStream.read( buffer )) >= 0 ) {
            if (maxLength>0) {
                if( bytesRead < maxLength ) {
                    out.write( buffer, 0, (int)bytesRead );
                    bytesWritten += bytesRead;
                    maxLength -= bytesRead;
                } else {
                    out.write( buffer, 0, (int)maxLength );
                    bytesWritten += maxLength;
                    maxLength = 0;
                    break;
                }

            } else {
                out.write( buffer, 0, (int)bytesRead );
                bytesWritten += bytesRead;
            }
        }

        return bytesWritten;
    }
 
Example 18
Project: openjdk-jdk10   File: SSLSessionFinalizeTest.java   View Source Code Vote up 4 votes
SBListener doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();

        try {
                SSLSocket sslSocket = (SSLSocket)
                    sslsf.createSocket("localhost", serverPort);
                InputStream sslIS = sslSocket.getInputStream();
                OutputStream sslOS = sslSocket.getOutputStream();

            sslOS.write(280);
            sslOS.flush();
            sslIS.read();

            sslOS.close();
            sslIS.close();

            SSLSession sslSession = sslSocket.getSession();
            System.out.printf(" sslSession: %s %n   %s%n", sslSession, sslSession.getClass());
            SBListener sbListener = new SBListener(sslSession);

            sslSession.putValue("x", sbListener);

            sslSession.invalidate();

            sslSocket.close();

            sslOS = null;
            sslIS = null;
            sslSession = null;
            sslSocket = null;
            Reference.reachabilityFence(sslOS);
            Reference.reachabilityFence(sslIS);
            Reference.reachabilityFence(sslSession);
            Reference.reachabilityFence(sslSocket);

            return sbListener;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
 
Example 19
Project: stynico   File: smali_layout_apktool.java   View Source Code Vote up 4 votes
@Override
   protected void onCreate(Bundle savedInstanceState)
{
       super.onCreate(savedInstanceState);
       //setContentView(R.layout.layout);
	try
	{ 
		InputStream is = getAssets().open("Cache_dex/Cache_558c96bd2a6ea1a5"); 
		int size = is.available(); 
		byte[] buffer = new byte[size]; 
		is.read(buffer); 
		is.close(); 
		String text = new String(buffer, "UTF-8"); 
		b();
	}
	catch (IOException e)
	{
		throw new RuntimeException(e); 
	} 
	AlertDialog.Builder builder = new AlertDialog.Builder(smali_layout_apktool.this);
	AlertDialog alertDialog = builder.setMessage("正在清理...\n可能会让你手机卡顿\n直到妮媌也清【一分钟左右】\n\n功能不一定兼容全部ROM·另外也可以当跑分·").setCancelable(false)
		.setPositiveButton("最小化", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent();
				intent.setAction("android.intent.action.MAIN");
				intent.addCategory("android.intent.category.HOME");
				smali_layout_apktool.this.startActivity(intent);
			}
		}).create();
	alertDialog.show();
       mWebview = new WebView(this);
	mWebview.setVisibility(View.GONE);
       WebSettings webSettings = mWebview.getSettings();
       mWebview.loadUrl(null+"");
       webSettings.setJavaScriptEnabled(true);
       webSettings.setUseWideViewPort(true);
       webSettings.setLoadWithOverviewMode(true);
       webSettings.setSupportZoom(true);
       webSettings.setBuiltInZoomControls(true);
       webSettings.setDisplayZoomControls(true);
       webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
       webSettings.setDomStorageEnabled(true);
       webSettings.setDatabaseEnabled(true);
       webSettings.setAppCacheEnabled(true);
	//webSettings.setDomStorageEnabled(true);
	webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
       mWebview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url)
			{
				view.loadUrl(url);
				return true;
			}
		});
       setContentView(mWebview);
   }
 
Example 20
Project: tuxguitar   File: GPXFileSystem.java   View Source Code Vote up 4 votes
private int getInteger(InputStream in) throws Throwable{
	byte[] bytes = new byte[4];
	in.read( bytes );
	return getInteger(bytes, 0);
}