Example usage for java.io FileInputStream close

List of usage examples for java.io FileInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

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

Usage

From source file:MainClass.java

public static void main(String[] args) {

    int bufferSize = 8192;
    // create output stream
    String sourceFileName = "data.txt";
    String zipname = sourceFileName + ".gz";
    GZIPOutputStream zipout;//from  w  w w. j a v  a 2 s  . co m
    try {
        FileOutputStream out = new FileOutputStream(zipname);
        zipout = new GZIPOutputStream(out);
    } catch (IOException e) {
        System.out.println("Couldn't create " + zipname + ".");
        return;
    }
    byte[] buffer = new byte[bufferSize];
    // compress the file
    try {
        FileInputStream in = new FileInputStream(sourceFileName);
        int length;
        while ((length = in.read(buffer, 0, bufferSize)) != -1)
            zipout.write(buffer, 0, length);
        in.close();
    } catch (IOException e) {
        System.out.println("Couldn't compress " + sourceFileName + ".");
    }
    try {
        zipout.close();
    } catch (IOException e) {
    }
}

From source file:Example2.java

public static void main(String args[])
        throws IOException, ParseException, DScabiClientException, DScabiException, java.text.ParseException {
    System.out.println("Example2");

    DMeta meta = new DMeta("localhost", "5000");

    DFile f = new DFile(meta);
    f.setNamespace("MyOrg.MyFiles");
    Date date = new Date();

    f.put("scabi:MyOrg.MyFiles:myfile1.txt", "myfile1.txt");
    f.put("myfile2.txt", "myfile2.txt");

    FileInputStream fis = new FileInputStream("myfile3.txt");
    f.put("scabi:MyOrg.MyFiles:myfile3.txt", fis);
    fis.close();

    f.copy("scabi:MyOrg.MyFiles:myfile4.txt", "scabi:MyOrg.MyFiles:myfile1.txt");
    f.copy("myfile5.txt", "scabi:MyOrg.MyFiles:myfile1.txt");

    f.get("scabi:MyOrg.MyFiles:myfile1.txt", "fileout1" + "_" + date.toString() + ".txt");
    f.get("myfile2.txt", "fileout2" + "_" + date.toString() + ".txt");

    FileOutputStream fos = new FileOutputStream("fileout3" + "_" + date.toString() + ".txt");
    f.get("scabi:MyOrg.MyFiles:myfile1.txt", fos);
    fos.close();/*w w  w  .  j a  v a2  s .  com*/

    FileOutputStream fos2 = new FileOutputStream("fileout4" + "_" + date.toString() + ".txt");
    f.get("myfile2.txt", fos2);
    fos2.close();

    f.close();
    meta.close();
}

From source file:info.reborncraft.ImageManipulation.java

/**
 * @param args//from w  ww  . j  a  v a  2  s  .co m
 */
public static void main(String[] args) {
    File file = new File("server-icon.png");

    try {
        /*
         * Reading a Image file from file system
         */
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);
        imageInFile.close();
        /*
         * Converting Image byte array into Base64 String
         */
        String imageDataString = encodeImage(imageData);

        System.out.println(imageDataString);
    } catch (FileNotFoundException e) {
        System.out.println("Image not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }

}

From source file:Employee.java

public static void main(String[] args) {
    Employee e = null;/*from   w  w  w . j  a v a 2s.co  m*/
    try {
        FileInputStream fileIn = new FileInputStream("employee.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        e = (Employee) in.readObject();
        in.close();
        fileIn.close();
    } catch (IOException i) {
        i.printStackTrace();
        return;
    } catch (ClassNotFoundException c) {
        System.out.println("Employee class not found");
        c.printStackTrace();
        return;
    }
    System.out.println("Name: " + e.name);
    System.out.println("Address: " + e.address);
    System.out.println("SSN: " + e.SSN);
    System.out.println("Number: " + e.number);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String keystoreFile = "keyStoreFile.bin";
    String caAlias = "caAlias";
    String certToSignAlias = "cert";
    String newAlias = "newAlias";

    char[] password = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] caPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] certPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

    FileInputStream input = new FileInputStream(keystoreFile);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(input, password);//w  ww. j av  a 2s. c o m
    input.close();

    PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword);
    java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias);

    byte[] encoded = caCert.getEncoded();
    X509CertImpl caCertImpl = new X509CertImpl(encoded);

    X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME);

    java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword);
    encoded = cert.getEncoded();
    X509CertImpl certImpl = new X509CertImpl(encoded);
    X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    Date firstDate = new Date();
    Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);

    certInfo.set(X509CertInfo.VALIDITY, interval);

    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));

    certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer);

    AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
    X509CertImpl newCert = new X509CertImpl(certInfo);

    newCert.sign(caPrivateKey, "MD5WithRSA");

    keyStore.setKeyEntry(newAlias, privateKey, certPassword, new java.security.cert.Certificate[] { newCert });

    FileOutputStream output = new FileOutputStream(keystoreFile);
    keyStore.store(output, password);
    output.close();

}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("my.keystore"));
    try {//from   www.  j  a  va 2  s  .  c  o  m
        trustStore.load(instream, "nopassword".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" },
            null, SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:MainClass.java

public static void main(String args[]) {
    try {//w w  w  .  j av  a2 s  .  c  o  m
        FileInputStream fis = new FileInputStream(args[0]);

        BufferedInputStream bis = new BufferedInputStream(fis);

        int i;
        while ((i = bis.read()) != -1) {
            System.out.println(i);
        }
        fis.close();
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }
}

From source file:examples.StatePersistence.java

public static void main(String[] args) throws Exception {
    // Connect to localhost and use the travel-sample bucket
    final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build();

    // Don't do anything with control events in this example
    client.controlEventHandler(new ControlEventHandler() {
        @Override/*www. ja v a 2  s  . c o  m*/
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpSnapshotMarkerRequest.is(event)) {
                flowController.ack(event);
            }
            event.release();
        }
    });

    // Print out Mutations and Deletions
    client.dataEventHandler(new DataEventHandler() {
        @Override
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpMutationMessage.is(event)) {
                System.out.println("Mutation: " + DcpMutationMessage.toString(event));
                // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8);
            } else if (DcpDeletionMessage.is(event)) {
                System.out.println("Deletion: " + DcpDeletionMessage.toString(event));
            }
            event.release();
        }
    });

    // Connect the sockets
    client.connect().await();

    // Try to load the persisted state from file if it exists
    File file = new File(FILENAME);
    byte[] persisted = null;
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(FILENAME);
        persisted = IOUtils.toByteArray(fis);
        fis.close();
    }

    // if the persisted file exists recover, if not start from beginning
    client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY)
            .await();

    // Start streaming on all partitions
    client.startStreaming().await();

    // Persist the State ever 10 seconds
    while (true) {
        Thread.sleep(TimeUnit.SECONDS.toMillis(10));

        // export the state as a JSON byte array
        byte[] state = client.sessionState().export(StateFormat.JSON);

        // Write it to a file
        FileOutputStream output = new FileOutputStream(new File(FILENAME));
        IOUtils.write(state, output);
        output.close();

        System.out.println(System.currentTimeMillis() + " - Persisted State!");
    }
}

From source file:com.rabbitmq.examples.FileProducer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("p", "port", true, "broker port"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));

    CommandLineParser parser = new GnuParser();

    try {//from   www  . j a v a  2  s . c o m
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        if (exchange == null) {
            System.err.println("Please supply exchange name to send to (-e)");
            System.exit(2);
        }
        if (routingKey == null) {
            System.err.println("Please supply routing key to send to (-k)");
            System.exit(2);
        }
        ch.exchangeDeclare(exchange, exchangeType);

        for (String filename : cmd.getArgs()) {
            System.out.print("Sending " + filename + "...");
            File f = new File(filename);
            FileInputStream i = new FileInputStream(f);
            byte[] body = new byte[(int) f.length()];
            i.read(body);
            i.close();

            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("filename", filename);
            headers.put("length", (int) f.length());
            BasicProperties props = new BasicProperties.Builder().headers(headers).build();
            ch.basicPublish(exchange, routingKey, props, body);
            System.out.println(" done.");
        }

        conn.close();
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:Main.java

public static void main(String[] args) {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    client.connect("ftp.domain.com");
    client.login("admin", "secret");

    String filename = "Touch.dat";
    fis = new FileInputStream(filename);
    client.storeFile(filename, fis);/*  w ww  . j  a  v  a  2 s  .  c om*/
    client.logout();
    fis.close();
}