Example usage for java.io InputStream read

List of usage examples for java.io InputStream read

Introduction

In this page you can find the example usage for java.io InputStream read.

Prototype

public abstract int read() throws IOException;

Source Link

Document

Reads the next byte of data from the input stream.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    InputStream is = new FileInputStream("C://test.txt");

    System.out.println("Characters printed:");
    // create new buffered reader

    // reads and prints BufferedReader
    System.out.println((char) is.read());
    System.out.println((char) is.read());

    // mark invoked at this position
    is.mark(0);/*  w  w  w  . j a  va 2  s.  c o m*/
    System.out.println("mark() invoked");
    System.out.println((char) is.read());
    System.out.println((char) is.read());

    // reset() repositioned the stream to the mark
    if (is.markSupported()) {
        is.reset();
        System.out.println("reset() invoked");
        System.out.println((char) is.read());
        System.out.println((char) is.read());
    } else {
        System.out.print("InputStream does not support reset()");
    }
    is.close();
}

From source file:Main.java

public static void main(String[] args) {
    byte[] b = { 'h', 'e', 'l', 'l', 'o' };
    try {//from  w w w. j av  a2s . c  o  m

        // create a new output stream
        OutputStream os = new FileOutputStream("test.txt");

        // craete a new input stream
        InputStream is = new FileInputStream("test.txt");

        // write something
        os.write(b);

        // read what we wrote
        for (int i = 0; i < b.length; i++) {
            System.out.print((char) is.read());
        }
        os.close();
        is.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.tc.simple.apn.quicktests.Test.java

/**
 * @param args/* ww w .  j av  a  2  s.  c o m*/
 */

public static void main(String[] args) {
    SSLSocket socket = null;

    try {
        String host = "gateway.sandbox.push.apple.com";
        int port = 2195;

        String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f";
        System.out.println(token.toCharArray().length);

        //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223";

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray());
        KeyManagerFactory keyMgrFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
        SSLSocketFactory socketFactory = sslContext.getSocketFactory();

        socket = (SSLSocket) socketFactory.createSocket(host, port);
        String[] cipherSuites = socket.getSupportedCipherSuites();
        socket.setEnabledCipherSuites(cipherSuites);
        socket.startHandshake();

        char[] t = token.toCharArray();
        byte[] b = Hex.decodeHex(t);

        OutputStream outputstream = socket.getOutputStream();

        String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}";

        int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        DataOutputStream dos = new DataOutputStream(bout);

        //command
        dos.writeByte(1);

        //id
        dos.writeInt(900);

        //expiry
        dos.writeInt(expiry);

        //token length.
        dos.writeShort(b.length);

        //token
        dos.write(b);

        //payload length
        dos.writeShort(payload.length());

        //payload.
        dos.write(payload.getBytes());

        byte[] byteMe = bout.toByteArray();

        socket.getOutputStream().write(byteMe);

        socket.setSoTimeout(900);
        InputStream in = socket.getInputStream();

        System.out.println(APNErrors.getError(in.read()));

        in.close();

        outputstream.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    FileOutputStream fouts = null;
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");
    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);

    OutputStream outs = s.getOutputStream();
    PrintStream out = new PrintStream(outs);
    InputStream ins = s.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(ins));

    out.println(args[0]);// w  w w .  j  a  va  2 s.  c  om
    fouts = new FileOutputStream("result.html");
    //  fouts = new FileOutputStream("result.gif");
    int kk;
    while ((kk = ins.read()) != -1) {
        fouts.write(kk);
    }
    in.close();
    fouts.close();
}

From source file:Main.java

public static void main(String[] args) {
    try {//w  ww  .j  a va 2s.  c  o  m

        OutputStream os = new FileOutputStream("test.txt");

        InputStream is = new FileInputStream("test.txt");

        // write something
        os.write('A');

        // flush the stream
        os.flush();

        // close the stream but it does nothing
        os.close();

        // read what we wrote
        System.out.println((char) is.read());
        is.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:ObfuscatingStream.java

/**
 * Obfuscates or unobfuscates the second command-line argument, depending on
 * whether the first argument starts with "o" or "u"
 * /*from   w w  w .  ja  v a2s .c  o m*/
 * @param args
 *            Command-line arguments
 * @throws IOException
 *             If an error occurs obfuscating or unobfuscating
 */
public static void main(String[] args) throws IOException {
    InputStream input = new ByteArrayInputStream(args[1].getBytes());
    StringBuilder toPrint = new StringBuilder();
    if (args[0].startsWith("o")) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        OutputStream out = obfuscate(bytes);
        int read = input.read();
        while (read >= 0) {
            out.write(read);
            read = input.read();
        }
        byte[] receiptBytes = bytes.toByteArray();
        for (int b = 0; b < receiptBytes.length; b++) {
            int chr = (receiptBytes[b] + 256) % 256;
            toPrint.append(HEX_CHARS[chr >>> 4]);
            toPrint.append(HEX_CHARS[chr & 0xf]);
        }
    } else if (args[0].startsWith("u")) {
        input = unobfuscate(input);
        InputStreamReader reader = new InputStreamReader(input);

        int read = reader.read();
        while (read >= 0) {
            toPrint.append((char) read);
            read = reader.read();
        }
    } else
        throw new IllegalArgumentException("First argument must start with o or u");
    System.out.println(toPrint.toString());
}

From source file:jfs.sync.meta.MetaFileStorageAccess.java

/**
 *
 * Extract one file from encrypted repository.
 *
 * TODO: list directories/*from w  ww. j a  v  a2 s. c o m*/
 *
 */
public static void main(String[] args) throws Exception {
    final String password = args[0];
    MetaFileStorageAccess storage = new MetaFileStorageAccess("Twofish", false) {

        protected String getPassword(String relativePath) {
            String result = "";

            String pwd = password;

            int i = 0;
            int j = relativePath.length() - 1;
            while ((i < pwd.length()) || (j >= 0)) {
                if (i < pwd.length()) {
                    result += pwd.charAt(i++);
                } // if
                if (j >= 0) {
                    result += relativePath.charAt(j--);
                } // if
            } // while

            return result;
        } // getPassword()
    };
    String encryptedPath = args[2];
    String[] elements = encryptedPath.split("\\\\");
    String path = "";
    for (int i = 0; i < elements.length; i++) {
        String encryptedName = elements[i];
        String plain = storage.getDecryptedFileName(path, encryptedName);
        path += storage.getSeparator();
        path += plain;
        System.out.println(path);
    } // for

    String cipherSpec = storage.getCipherSpec();
    byte[] credentials = storage.getFileCredentials(path);
    Cipher cipher = SecurityUtils.getCipher(cipherSpec, Cipher.DECRYPT_MODE, credentials);

    InputStream is = storage.getInputStream(args[1], path);
    is = JFSEncryptedStream.createInputStream(is, JFSEncryptedStream.DONT_CHECK_LENGTH, cipher);
    int b = 0;
    while (b >= 0) {
        b = is.read();
        System.out.print((char) b);
    } // while
    is.close();
}

From source file:innovimax.quixproc.datamodel.generator.json.AJSONGenerator.java

public static void main(String[] args)
        throws JsonParseException, IOException, InstantiationException, IllegalAccessException {

    /*/*from  w w  w  .  j a va  2s.  c  o  m*/
     * final byte[][] patterns = { // empty object is allowed
     * 
     * "\"A\":1".getBytes(), // first used only once ",\"A\":1".getBytes()
     * }; BoxedArray baA = new BoxedArray(patterns, 1, 2); for (int i = 0; i
     * <Integer.MAX_VALUE; i++) { baA.nextUnique(); }
     * 
     * 
     * System.out.println(display(patterns[1]));
     */
    JsonFactory f = new JsonFactory();
    f.disable(Feature.ALLOW_COMMENTS);
    f.disable(Feature.ALLOW_SINGLE_QUOTES);
    // AGenerator generator = instance(ATreeGenerator.Type.HIGH_DENSITY);
    AGenerator generator = instance(FileExtension.JSON, TreeType.HIGH_NODE_DEPTH, SpecialType.STANDARD);

    InputStream is = generator.getInputStream(50, Unit.MBYTE, Variation.NO_VARIATION);
    if (false) {
        int c;
        while ((c = is.read()) != -1) {
            System.out.println(display((byte) (c & 0xFF)));
        }
    } else {
        JsonParser p = f.createParser(is);
        p.enable(Feature.STRICT_DUPLICATE_DETECTION);

        while (p.nextToken() != JsonToken.END_OBJECT) {
            //
        }
    }
}

From source file:Base64.java

/** Testing. */
public static void main(String[] args) {

    String s = "Hello, world";
    s = "abcd";/*from  w w w.j a  v a 2s  .  co m*/
    //s = System.getProperties().toString();
    //System.out.println( s + ": \n [" + encode( s ) + "]\n [" + decode(encode(s)) + "]" );

    byte[] b = encodeString(s).getBytes();
    byte[] c = decode(b, 0, b.length);

    System.out.println("\n\n" + s + ":" + new String(b) + ":" + new String(c));

    try {
        FileInputStream fis = new FileInputStream("c:\\abcd.txt");
        InputStream b64is = new InputStream(fis, DECODE);
        int ib = 0;
        while ((ib = b64is.read()) > 0) { //System.out.print( new String( ""+(char)ib ) );
        }
    } // end try
    catch (Exception e) {

        e.printStackTrace();
    }
}

From source file:com.lxf.spider.client.QuickStart.java

public static void main(String[] args) throws Exception {
    InputStream input = null;
    OutputStream output = null;/*from  w w w .j a v  a2 s .c o m*/
    //httpclient
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //get
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/pdqx.jc.web/cen/center.html");
        //
        CloseableHttpResponse response1 = httpclient.execute(httpGet);

        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            //???
            int statusCode = response1.getStatusLine().getStatusCode();
            //??200?
            if (statusCode == HttpStatus.SC_OK) {
                //                  input = httpGet.getRequestLine();
                System.out.println(response1.getStatusLine());
                //
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                input = entity1.getContent();
                output = new FileOutputStream("d:/lxf.data");
                //?
                int tempByte = -1;
                while ((tempByte = input.read()) > 0) {
                    output.write(tempByte);
                }
                EntityUtils.consume(entity1);
                //?
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }

        } finally {
            response1.close();
        }

        /*HttpPost httpPost = new HttpPost("http://targethost/login");
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
                
        try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        } finally {
        response2.close();
        }*/
    } finally {
        httpclient.close();
    }
}