Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:Main.java

public static void main(String[] args) {
    try {//w w w  . j  a va2s .c o m
        // create a new process
        Process p = Runtime.getRuntime().exec("notepad.exe");

        // get the input stream of the process and print it
        InputStream in = p.getInputStream();
        for (int i = 0; i < in.available(); i++) {
            System.out.println(in.read());
        }

        // wait for 10 seconds and then destroy the process
        Thread.sleep(10000);
        p.destroy();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:Main.java

public static void main(String[] args) {
    try {// ww  w .ja  va  2  s .  c om
        // create a new process
        Process p = Runtime.getRuntime().exec("notepad.exe");

        // get the error stream of the process and print it
        InputStream error = p.getErrorStream();
        for (int i = 0; i < error.available(); i++) {
            System.out.println(error.read());
        }

        // wait for 10 seconds and then destroy the process
        Thread.sleep(10000);
        p.destroy();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:Main.java

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

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

    // invoke available
    int i = is.available();

    // number of bytes available is printed
    System.out.println(i);/*from  w w w .  ja  v a  2s  .c  om*/

    // releases any system resources associated with the stream
    is.close();

    // throws io exception on available() invocation
    i = is.available();
    System.out.println(i);

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(443);
    while (true) {
        Socket s = ss.accept();//from   w w  w.ja  v  a2  s .c o  m
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = null;
        String request = null;
        String refer = null;

        while ((info = in.readLine()) != null) {
            if (info.startsWith("GET")) {
                request = info;
            }
            if (info.startsWith("Referer:")) {
                refer = info;
            }
            if (info.equals(""))
                break;
        }
        if (request != null) {
            out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
            int sp1 = request.indexOf(' ');
            int sp2 = request.indexOf(' ', sp1 + 1);
            String filename = request.substring(sp1 + 2, sp2);
            if (refer != null) {
                sp1 = refer.indexOf(' ');
                refer = refer.substring(sp1 + 1, refer.length());
                if (!refer.endsWith("/")) {
                    refer = refer + "/";
                }
                filename = refer + filename;
            }
            URL con = new URL(filename);
            InputStream gotoin = con.openStream();
            int n = gotoin.available();
            byte buf[] = new byte[1024];
            out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
            out.println("Content_Length:" + n + "\n");
            while ((n = gotoin.read(buf)) >= 0) {
                out.write(buf, 0, n);
            }
            out.close();
            s.close();
            in.close();
        }
    }
}

From source file:Main.java

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

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

    DataInputStream dis = new DataInputStream(is);

    int count = is.available();

    byte[] bs = new byte[count];

    dis.read(bs);//ww  w. j  a  v a 2s.co  m

    for (byte b : bs) {
        char c = (char) b;
        System.out.print(c);
    }

}

From source file:Main.java

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

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

    DataInputStream dis = new DataInputStream(is);

    int count = is.available();

    byte[] bs = new byte[count];

    dis.read(bs, 4, 3);//from   w  w  w.j  a v a  2  s.  c  om

    for (byte b : bs) {
        char c = (char) b;

        if (b == 0) {
            c = '0';
        }
        System.out.print(c);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InputStream is = new FileInputStream("c:/test.txt");

    InputStreamReader isr = new InputStreamReader(is);

    BufferedReader br = new BufferedReader(isr);

    char[] cbuf = new char[is.available()];

    br.read(cbuf, 2, 10);//from  www  .  ja  v  a 2s . co m

    for (char c : cbuf) {
        if (c == (char) 0) {
            c = '*';
        }
        // prints characters
        System.out.print(c);
    }
}

From source file:ImportKey.java

/**
 * <p>/* w  w  w  .  j a  va 2s.c  o  m*/
 * Takes two file names for a key and the certificate for the key, and
 * imports those into a keystore. Optionally it takes an alias for the key.
 * <p>
 * The first argument is the filename for the key. The key should be in
 * PKCS8-format.
 * <p>
 * The second argument is the filename for the certificate for the key.
 * <p>
 * If a third argument is given it is used as the alias. If missing, the key
 * is imported with the alias importkey
 * <p>
 * The name of the keystore file can be controlled by setting the keystore
 * property (java -Dkeystore=mykeystore). If no name is given, the file is
 * named <code>keystore.ImportKey</code> and placed in your home directory.
 * 
 * @param args
 *            [0] Name of the key file, [1] Name of the certificate file [2]
 *            Alias for the key.
 **/
public static void main(String args[]) {

    // change this if you want another password by default
    String keypass = "password";

    // change this if you want another alias by default
    String defaultalias = "tomcat";

    // change this if you want another keystorefile by default
    String keystorename = null;

    // parsing command line input
    String keyfile = "";
    String certfile = "";
    if (args.length < 3 || args.length > 4) {
        System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]");
        System.exit(0);
    } else {
        keystorename = args[0];
        keyfile = args[1];
        certfile = args[2];
        if (args.length > 3)
            defaultalias = args[3];
    }

    try {
        // initializing and clearing keystore
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(null, keypass.toCharArray());
        System.out.println("Using keystore-file : " + keystorename);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
        ks.load(new FileInputStream(keystorename), keypass.toCharArray());

        // loading Key
        InputStream fl = fullStream(keyfile);
        byte[] key = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(key, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key);
        PrivateKey ff = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certstream = fullStream(certfile);

        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        if (c.size() == 1) {
            certstream = fullStream(certfile);
            System.out.println("One certificate, no chain.");
            Certificate cert = cf.generateCertificate(certstream);
            certs[0] = cert;
        } else {
            System.out.println("Certificate chain length: " + c.size());
            certs = (Certificate[]) c.toArray(new Certificate[c.size()]);
        }

        // storing keystore
        ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs);
        System.out.println("Key and certificate stored.");
        System.out.println("Alias:" + defaultalias + "  Password:" + keypass);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

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

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

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

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

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

        // write something else
        os.write('B');

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

}

From source file:hk.hku.cecid.corvus.http.AS2EnvelopQuerySender.java

/**
 * The main method is for CLI mode./*from   w w w.  j a v  a 2  s.c om*/
 */
public static void main(String[] args) {
    try {
        java.io.PrintStream out = System.out;

        if (args.length < 2) {
            out.println("Usage: as2-envelop [config-xml] [log-path]");
            out.println();
            out.println("Example: as2-envelop ./config/as2-envelop/as2-request.xml ./logs/as2-envelop.log");
            System.exit(1);
        }

        out.println("------------------------------------------------------");
        out.println("       AS2 Envelop Queryer       ");
        out.println("------------------------------------------------------");

        // Initialize the logger.
        out.println("Initialize logger .. ");
        // The logger path is specified at the last argument.
        FileLogger logger = new FileLogger(new File(args[args.length - 1]));

        // Initialize the query parameter.
        out.println("Importing AS2 administrative sending parameters ... ");
        AS2AdminData acd = DataFactory.getInstance()
                .createAS2AdminDataFromXML(new PropertyTree(new File(args[0]).toURI().toURL()));

        boolean historyQueryNeeded = false;
        AS2MessageHistoryRequestData queryData = new AS2MessageHistoryRequestData();
        if (acd.getMessageIdCriteria() == null || acd.getMessageIdCriteria().trim().equals("")) {

            historyQueryNeeded = true;

            // print command prompt
            out.println("No messageID was specified!");
            out.println("Start querying message repositry ...");

            String endpoint = acd.getEnvelopQueryEndpoint();
            String host = endpoint.substring(0, endpoint.indexOf("/corvus"));
            host += "/corvus/httpd/as2/msg_history";
            queryData.setEndPoint(host);
        } /*
            If the user has entered message id but no messagebox, 
            using the messageid as serach criteria and as 
            user to chose his target message
          */
        else if (acd.getMessageBoxCriteria() == null || acd.getMessageBoxCriteria().trim().equals("")) {

            historyQueryNeeded = true;

            // print command prompt
            out.println("Message Box value haven't specified.");
            out.println("Start query message whcih matched with messageID: " + acd.getMessageIdCriteria());

            String endpoint = acd.getEnvelopQueryEndpoint();
            String host = endpoint.substring(0, endpoint.indexOf("/corvus"));
            host += "/corvus/httpd/as2/msg_history";

            queryData.setEndPoint(host);
            queryData.setMessageId(acd.getMessageIdCriteria());
        }
        //Debug Message
        System.out.println("history Endpoint: " + queryData.getEndPoint());
        System.out.println("Repositry Endpoint: " + acd.getEnvelopQueryEndpoint());

        if (historyQueryNeeded) {
            List msgList = listAvailableMessage(queryData, logger);

            if (msgList == null || msgList.size() == 0) {
                out.println();
                out.println();
                out.println("No stream data found in repositry...");
                out.println("Please view log for details .. ");
                return;
            }

            int selection = promptForSelection(msgList);

            if (selection == -1) {
                return;
            }

            String messageID = (String) ((List) msgList.get(selection)).get(0);
            String messageBox = (String) ((List) msgList.get(selection)).get(1);
            acd.setMessageIdCriteria(messageID);
            acd.setMessageBoxCriteria(messageBox.toUpperCase());
            out.println();
            out.println();
            out.println("Start download targeted message envelop ...");
        }

        // Initialize the sender.
        out.println("Initialize AS2 HTTP data service client... ");
        AS2EnvelopQuerySender sender = new AS2EnvelopQuerySender(logger, acd);

        out.println("Sending    AS2 HTTP Envelop Query request ... ");
        sender.run();

        out.println();
        out.println("                    Sending Done:                   ");
        out.println("----------------------------------------------------");
        out.println("The Message Envelope : ");
        InputStream eins = sender.getEnvelopStream();
        if (eins.available() == 0) {
            out.println("No stream data found.");
            out.println("The message envelop does not exist for message id " + sender.getMessageIdToDownload()
                    + " and message box " + sender.getMessageBoxToDownload());
        } else
            IOHandler.pipe(sender.getEnvelopStream(), out);

        out.println("Please view log for details .. ");
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}