Example usage for java.io InputStream close

List of usage examples for java.io InputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:examples.ftp.FTPSExample.java

public static final void main(String[] args) throws NoSuchAlgorithmException {
    int base = 0;
    boolean storeFile = false, binaryTransfer = false, error = false;
    String server, username, password, remote, local;
    String protocol = "SSL"; // SSL/TLS
    FTPSClient ftps;//from w  ww.  j av  a  2s.c  om

    for (base = 0; base < args.length; base++) {
        if (args[base].startsWith("-s"))
            storeFile = true;
        else if (args[base].startsWith("-b"))
            binaryTransfer = true;
        else
            break;
    }

    if ((args.length - base) != 5) {
        System.err.println(USAGE);
        System.exit(1);
    }

    server = args[base++];
    username = args[base++];
    password = args[base++];
    remote = args[base++];
    local = args[base];

    ftps = new FTPSClient(protocol);

    ftps.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

    try {
        int reply;

        ftps.connect(server);
        System.out.println("Connected to " + server + ".");

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftps.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftps.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftps.isConnected()) {
            try {
                ftps.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        ftps.setBufferSize(1000);

        if (!ftps.login(username, password)) {
            ftps.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftps.getSystemName());

        if (binaryTransfer)
            ftps.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftps.enterLocalPassiveMode();

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftps.storeFile(remote, input);

            input.close();
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftps.retrieveFile(remote, output);

            output.close();
        }

        ftps.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftps.isConnected()) {
            try {
                ftps.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:AESTest.java

public static void main(String[] args) {
    try {//from   w  w  w  . j ava 2 s. com
        if (args[0].equals("-genkey")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(key);
            out.close();
        } else {
            int mode;
            if (args[0].equals("-encrypt"))
                mode = Cipher.ENCRYPT_MODE;
            else
                mode = Cipher.DECRYPT_MODE;

            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key key = (Key) keyIn.readObject();
            keyIn.close();

            InputStream in = new FileInputStream(args[1]);
            OutputStream out = new FileOutputStream(args[2]);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(mode, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    InputStream fis = new FileInputStream("a.exe");

    byte[] buffer = new byte[1024];
    MessageDigest complete = MessageDigest.getInstance("MD5");
    int numRead;/* ww  w.ja  v a2  s  .com*/
    do {
        numRead = fis.read(buffer);
        if (numRead > 0) {
            complete.update(buffer, 0, numRead);
        }
    } while (numRead != -1);
    fis.close();

    byte[] b = complete.digest();
    String result = "";
    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    System.out.println(result);

}

From source file:Main.java

public static void main(String[] args) {
    try {//from www  .j  a v a 2s.c o  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:RSATest.java

public static void main(String[] args) {
    try {/*  w w w  . j av  a 2s.c  om*/
        if (args[0].equals("-genkey")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-encrypt")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();

            // wrap with RSA public key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new FileInputStream(args[1]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            in.close();
            out.close();
        } else {
            DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            // unwrap with RSA private key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key privateKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            OutputStream out = new FileOutputStream(args[2]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

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

    URL u = new URL("http://www.java2s.com/binary.dat");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
        throw new IOException("This is not a binary file.");
    }/*from   w  w  w  . j  a  va  2s  . c o m*/
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
        bytesRead = in.read(data, offset, data.length - offset);
        if (bytesRead == -1)
            break;
        offset += bytesRead;
    }
    in.close();

    if (offset != contentLength) {
        throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    }

    String filename = u.getFile().substring(filename.lastIndexOf('/') + 1);
    FileOutputStream out = new FileOutputStream(filename);
    out.write(data);
    out.flush();
    out.close();
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuthFormatURL.java

public static void main(String[] args) {
    // TODO code application logic here
    Map<String, String> params = new HashMap<String, String>();
    params.put("host", "10.49.28.3");
    params.put("port", "8081");
    params.put("reportName", "vencimientos");
    params.put("parametros", "feini=2016-09-30&fefin=2016-09-30");
    StrSubstitutor sub = new StrSubstitutor(params, "{", "}");
    String urlTemplate = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{parametros}";
    String url = sub.replace(urlTemplate);

    try {/*from   www.  ja v  a  2  s .com*/
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jasperadmin", "jasperadmin"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java

public static void main(String[] args) {
    // TODO code application logic here

    String host = "10.49.28.3";
    String port = "8081";
    String reportName = "vencimientos";
    String params = "feini=2016-09-30&fefin=2016-09-30";
    String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}";
    url = url.replace("{host}", host);
    url = url.replace("{port}", port);
    url = url.replace("{reportName}", reportName);
    url = url.replace("{params}", params);

    try {/*from   ww  w.java 2  s.  c  om*/
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.dlut.mycloudserver.service.performancemonitor.PerformanceListener.java

public static void main(String[] args) {
    long t1 = System.currentTimeMillis();

    String url = "http://127.0.0.1:8001";
    URLConnection conn;/* w  w  w  .j  a  va 2s.  com*/
    try {
        conn = new URL(url).openConnection();
        conn.setConnectTimeout(1000);
        conn.setReadTimeout(1000);
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String res = br.readLine();
        br.close();
        is.close();
        JSONObject jsonRes = JSON.parseObject(res);
        double loadAverage = jsonRes.getDoubleValue("loadAverage");
        System.out.println(loadAverage);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    long t2 = System.currentTimeMillis();

    System.out.println((t2 - t1) + "ms");
}

From source file:Main.java

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

    byte[] buffer = new byte[5];

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

    System.out.println("Characters printed:");

    // read stream data into buffer
    is.read(buffer);/* ww  w . j a v  a  2s  .c o m*/

    // for each byte in the buffer
    for (byte b : buffer) {
        // convert byte to character
        char c = (char) b;

        // prints character
        System.out.print(c);
    }
    is.close();
}