Example usage for java.io OutputStream close

List of usage examples for java.io OutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:Main.java

public static void main(String[] args) {
    byte[] b = { 'h', 'e', 'l', 'l', 'o' };
    try {/*ww  w  .  ja  va2 s .  c  om*/

        // 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:org.sbs.util.BinaryDateDwonLoader.java

/**
 * @param args//  w w w. j a va  2s.  c  o  m
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String img = "http://apollo.s.dpool.sina.com.cn/nd/dataent/moviepic/pics/157/moviepic_8d48be1e004c5b05464a7a427d6722e4.jpg";
    BinaryDateDwonLoader dateDwonLoader = BinaryDateDwonLoader.getInstance();
    PageFetchResult result = dateDwonLoader.fetchHeader(img);
    try {
        OutputStream outputStream = new FileOutputStream(
                new File("d:\\" + img.substring(img.lastIndexOf('/') + 1)));
        result.getEntity().writeTo(outputStream);
        outputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.hurence.logisland.utils.avro.eventgenerator.DataGenerator.java

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

    // load and verify the options
    CommandLineParser parser = new PosixParser();
    Options opts = loadOptions();//from ww w  . j av a  2  s .  c om

    CommandLine cmd = null;
    try {
        cmd = parser.parse(opts, args);
    } catch (org.apache.commons.cli.ParseException parseEx) {
        LOG.error("Invalid option");
        printHelp(opts);
        return;
    }

    // check for necessary options
    String fileLoc = cmd.getOptionValue("schemaLocation");
    if (fileLoc == null) {
        LOG.error("schemaLocation not specified");
        printHelp(opts);
    }

    //get string length and check if min is greater than 0

    // Generate the record
    File schemaFile = new File(fileLoc);
    DataGenerator dataGenerator = new DataGenerator(schemaFile);
    GenericRecord record = dataGenerator.generateRandomRecord();
    if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) {
        String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME);
        OutputStream outs = System.out;
        if (!outname.equals("-")) {
            outs = new FileOutputStream(outname);
        }
        printAvroJson(record, outs);
        if (!outname.equals("-")) {
            outs.close();
        }
    } else {
        DataGenerator.prettyPrint(record);
    }

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = sf.createSocket(HOST, PORT);
    OutputStream out = s.getOutputStream();
    out.write("\nConnection established.\n\n".getBytes());
    out.flush();// w ww  . j a  v  a 2s .  c  o  m
    int theCharacter = 0;
    theCharacter = System.in.read();
    while (theCharacter != '~') // The '~' is an escape character to exit
    {
        out.write(theCharacter);
        out.flush();
        theCharacter = System.in.read();
    }

    out.close();
    s.close();
}

From source file:com.hurence.logisland.util.avro.eventgenerator.DataGenerator.java

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

    // load and verify the options
    CommandLineParser parser = new PosixParser();
    Options opts = loadOptions();/*from   www.jav a2 s .com*/

    CommandLine cmd = null;
    try {
        cmd = parser.parse(opts, args);
    } catch (org.apache.commons.cli.ParseException parseEx) {
        logger.error("Invalid option");
        printHelp(opts);
        return;
    }

    // check for necessary options
    String fileLoc = cmd.getOptionValue("schemaLocation");
    if (fileLoc == null) {
        logger.error("schemaLocation not specified");
        printHelp(opts);
    }

    //getField string length and check if min is greater than 0

    // Generate the record
    File schemaFile = new File(fileLoc);
    DataGenerator dataGenerator = new DataGenerator(schemaFile);
    GenericRecord record = dataGenerator.generateRandomRecord();
    if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) {
        String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME);
        OutputStream outs = System.out;
        if (!outname.equals("-")) {
            outs = new FileOutputStream(outname);
        }
        printAvroJson(record, outs);
        if (!outname.equals("-")) {
            outs.close();
        }
    } else {
        DataGenerator.prettyPrint(record);
    }

}

From source file:Main.java

public static void main(String[] args) {
    try {/*from  w ww .java  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:MainClass.java

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

    char[] passphrase = "sasquatch".toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream(".keystore"), passphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(keystore);/*www .  ja va 2  s . co  m*/

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManager[] trustManagers = tmf.getTrustManagers();

    context.init(null, trustManagers, null);

    SSLSocketFactory sf = context.getSocketFactory();

    Socket s = sf.createSocket(HOST, PORT);
    OutputStream out = s.getOutputStream();
    out.write("\nConnection established.\n\n".getBytes());

    int theCharacter = 0;
    theCharacter = System.in.read();
    while (theCharacter != '~') // The '~' is an escape character to exit
    {
        out.write(theCharacter);
        out.flush();
        theCharacter = System.in.read();
    }

    out.close();
    s.close();
}

From source file:com.linkedin.databus.eventgenerator.DataGenerator.java

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

    // load and verify the options
    CommandLineParser parser = new PosixParser();
    Options opts = loadOptions();// w w  w . jav a2  s  .com

    CommandLine cmd = null;
    try {
        cmd = parser.parse(opts, args);
    } catch (org.apache.commons.cli.ParseException parseEx) {
        LOG.error("Invalid option");
        printHelp(opts);
        return;
    }

    if (cmd.hasOption('l')) {
        String log4jPropFile = cmd.getOptionValue('l');
        PropertyConfigurator.configure(log4jPropFile);
        LOG.info("Using custom logging settings from file " + log4jPropFile);
    } else {
        PatternLayout defaultLayout = new PatternLayout("%d{ISO8601} +%r [%t] (%p) {%c{1}} %m%n");
        ConsoleAppender defaultAppender = new ConsoleAppender(defaultLayout);

        Logger.getRootLogger().removeAllAppenders();
        Logger.getRootLogger().addAppender(defaultAppender);

        LOG.info("Using default logging settings");
    }

    // check for necessary options
    String fileLoc = cmd.getOptionValue("schemaLocation");
    if (fileLoc == null) {
        LOG.error("schemaLocation not specified");
        printHelp(opts);
    }

    //get string length and check if min is greater than 0

    // Generate the record
    File schemaFile = new File(fileLoc);
    DataGenerator dataGenerator = new DataGenerator(schemaFile);
    GenericRecord record = dataGenerator.generateRandomRecord();
    if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) {
        String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME);
        OutputStream outs = System.out;
        if (!outname.equals("-")) {
            outs = new FileOutputStream(outname);
        }
        printAvroJson(record, outs);
        if (!outname.equals("-")) {
            outs.close();
        }
    } else {
        DataGenerator.prettyPrint(record);
    }

}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * //w  w w  . j  a  v  a 2  s  . com
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:cn.zhuqi.mavenssh.web.util.FtpUtil.java

public static void main(String[] args) throws IOException {
    FtpUtil ftp = new FtpUtil();
    ftp.connect("192.168.0.111", 21, "zl123456", "p123456", false);
    OutputStream out = new FileOutputStream("C:/23456.jpg");
    ftp.getFile("data/2013532069.jpg", out);
    out.close();
    ftp.disconnect();//w  ww. ja  v a2s  .c om
}