Example usage for java.io BufferedWriter close

List of usage examples for java.io BufferedWriter close

Introduction

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

Prototype

@SuppressWarnings("try")
    public void close() throws IOException 

Source Link

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);//from ww w . j a  va 2 s .  c o m
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new FileInputStream(new File("input.xml")));
    File OutputDOM = new File("out.txt");
    FileOutputStream fostream = new FileOutputStream(OutputDOM);
    OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
    BufferedWriter bwriter = new BufferedWriter(oswriter);
    if (!OutputDOM.exists()) {
        OutputDOM.createNewFile();
    }
    visitRecursively(doc, bwriter);
    bwriter.close();
    oswriter.close();
    fostream.close();
}

From source file:com.diskoverorta.utils.JsonConvertor.java

public static void main(String[] args) throws IOException {
    JsonConvertor js = new JsonConvertor();
    js.JsonConvertor();/*from w w w  .  j av a  2 s . c om*/
    BufferedWriter bf = new BufferedWriter(new FileWriter("/home/serendio/jaroutput-json.txt"));
    bf.write(js.JsonConvertor());
    bf.newLine();
    bf.flush();
    bf.close();
}

From source file:com.bright.utils.rmDuplicateLines.java

public static void main(String args) {
    File monfile = new File(args);

    Set<String> userIdSet = new LinkedHashSet<String>();

    if (monfile.isFile() && monfile.getName().endsWith(".txt")) {
        try {//from   w  w w .j a  v  a 2s.c o  m
            List<String> content = FileUtils.readLines(monfile, Charset.forName("UTF-8"));
            userIdSet.addAll(content);

            Iterator<String> itr = userIdSet.iterator();
            StringBuffer output = new StringBuffer();
            while (itr.hasNext()) {

                output.append(itr.next() + System.getProperty("line.separator"));

            }

            BufferedWriter out = new BufferedWriter(new FileWriter(monfile));
            String outText = output.toString();

            out.write(outText);

            out.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

}

From source file:GetDirectDownload.java

/**
 * @param args// www . java 2  s .  c o m
 * @throws ParseException
 */
public static void main(final String[] args) throws ParseException {

    // you can either set the 2 strings above, or pass them in to this program
    if (args.length == 2) {
        USER_NAME = args[0];
        API_KEY = args[1];
    }

    // make sure the credentials got set
    if (USER_NAME.equals("<YOUR USER NAME>") || API_KEY.equals("<YOUR API KEY>")) {
        System.err.println(
                "You must either edit this example file and put in your username and apikey OR pass them in as program arguments");
        System.exit(1);
    }

    final ApiCredentials credentials = new ApiCredentials(USER_NAME, API_KEY);
    final NZBMatrixApi api = new NZBMatrixApi(credentials);

    try {
        // makes the request to the nzbMatrixAPI for a direct download of a particular post id
        final DirectDownloadResponse directDownload = api.getDirectDownload(314694);

        // save the nzb file to disk
        final String fileName = directDownload.getSuggestedFileName();

        final BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
        out.write(directDownload.getNzbFileContents());
        out.close();

        System.out.println("Nzb File Saved As: " + fileName);
    } catch (final ClientProtocolException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final NZBMatrixApiException e) {
        e.printStackTrace();
    }
}

From source file:Converter.java

public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream(new File("input.txt"));
    BufferedReader in = new BufferedReader(new InputStreamReader(fis, "SJIS"));

    FileOutputStream fos = new FileOutputStream(new File("output.txt"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));

    int len = 80;
    char buf[] = new char[len];

    int numRead;//  w  ww.  j a va  2  s  .c  o  m
    while ((numRead = in.read(buf, 0, len)) != -1)
        out.write(buf, 0, numRead);
    out.close();
    in.close();
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionSplitter.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("i", null, true, "Input file");
    options.addOption("o", null, true, "Output file prefix");
    options.addOption("p", null, true, "Comma separated probabilities e.g., 0.1,0.2,0.7.");
    options.addOption("n", null, true, "Comma separated part names, e.g., dev,test,train");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/*from www  .j  av a2 s. co m*/
        CommandLine cmd = parser.parse(options, args);

        InputStream input = null;

        if (cmd.hasOption("i")) {
            input = CompressUtils.createInputStream(cmd.getOptionValue("i"));
        } else {
            Usage("Specify Input file");
        }

        ArrayList<Double> probs = new ArrayList<Double>();
        String[] partNames = null;

        if (cmd.hasOption("p")) {
            String parts[] = cmd.getOptionValue("p").split(",");

            try {
                double sum = 0;
                for (String s : parts) {
                    double p = Double.parseDouble(s);
                    if (p <= 0 || p > 1)
                        Usage("All probabilities must be in the range (0,1)");
                    sum += p;
                    probs.add(p);
                }

                if (Math.abs(sum - 1.0) > Float.MIN_NORMAL) {
                    Usage("The sum of probabilities should be equal to 1, but it's: " + sum);
                }
            } catch (NumberFormatException e) {
                Usage("Can't convert some of the probabilities to a floating-point number.");
            }
        } else {
            Usage("Specify part probabilities.");
        }

        if (cmd.hasOption("n")) {
            partNames = cmd.getOptionValue("n").split(",");

            if (partNames.length != probs.size())
                Usage("The number of probabilities is not equal to the number of parts!");
        } else {
            Usage("Specify part names");
        }

        BufferedWriter[] outFiles = new BufferedWriter[partNames.length];

        if (cmd.hasOption("o")) {
            String outPrefix = cmd.getOptionValue("o");

            for (int partId = 0; partId < partNames.length; ++partId) {
                outFiles[partId] = new BufferedWriter(new OutputStreamWriter(
                        CompressUtils.createOutputStream(outPrefix + "_" + partNames[partId] + ".gz")));
            }
        } else {
            Usage("Specify Output file prefix");
        }

        System.out.println("Using probabilities:");
        for (int partId = 0; partId < partNames.length; ++partId)
            System.out.println(partNames[partId] + " : " + probs.get(partId));
        System.out.println("=================================================");

        XmlIterator inpIter = new XmlIterator(input, YahooAnswersReader.DOCUMENT_TAG);

        String oneRec = inpIter.readNext();
        int docNum = 1;
        for (; !oneRec.isEmpty(); ++docNum, oneRec = inpIter.readNext()) {
            double p = Math.random();

            if (docNum % 1000 == 0) {
                System.out.println(String.format("Processed %d documents", docNum));
            }

            BufferedWriter out = null;

            for (int partId = 0; partId < partNames.length; ++partId) {
                double pp = probs.get(partId);
                if (p <= pp || partId + 1 == partNames.length) {
                    out = outFiles[partId];
                    break;
                }
                p -= pp;
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");
            out.write(oneRec);
        }
        System.out.println(String.format("Processed %d documents", docNum - 1));
        // It's important to close all the streams here!
        for (BufferedWriter f : outFiles)
            f.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {// w w w  .  ja v  a 2s. c o m
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
            
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }
    } finally {
    httpclient.close();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.google.com");

    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
    BufferedWriter writer = new BufferedWriter(new FileWriter("data.html"));

    String line;//from www .  ja v a 2 s . c o m
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
        writer.write(line);
        writer.newLine();
    }

    reader.close();
    writer.close();
}

From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java

public static void main(String[] args) throws Exception {
    File root = new File("input_source");

    // load country-continent match
    countryToContinent//from w  w  w . j a va2 s .  c om
            .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties"));

    // creating files
    Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>();
    Map<String, Boolean> started = new HashMap<String, Boolean>();

    for (Object string : countryToContinent.keySet()) {
        String continent = countryToContinent.getProperty(string.toString());
        File dir = new File(root, continent);
        if (!dir.exists()) {
            dir.mkdir();
        }
        files.put(string.toString(), new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8")));
        System.out.println(continent + "/" + string + ".rdf");
        started.put(string.toString(), false);
    }

    System.out.println(started);

    Pattern countryPattern = Pattern
            .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>");
    long counter = 0;
    LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8");
    try {
        while (it.hasNext()) {
            String text = it.nextLine();
            if (text.startsWith("http://sws.geonames"))
                continue;

            // progress
            counter++;
            if (counter % 100000 == 0) {
                System.out.print("*");
            }
            //         System.out.println(counter);
            // get country
            String country = null;
            Matcher matcher = countryPattern.matcher(text);
            if (matcher.find()) {
                country = matcher.group(1);
            }
            //         System.out.println(country);
            if (country == null)
                country = "null";
            text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF",
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF");
            if (started.get(country) == null)
                throw new Exception("Unknow country " + country);
            if (started.get(country).booleanValue()) {
                // remove RDF opening
                text = text.substring(text.indexOf("<rdf:RDF "));
                text = text.substring(text.indexOf(">") + 1);
            }
            // remove RDF ending
            text = text.substring(0, text.indexOf("</rdf:RDF>"));
            files.get(country).append(text + "\n");
            if (!started.get(country).booleanValue()) {
                // System.out.println("Started with country " + country);
            }
            started.put(country, true);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

    for (Object string : countryToContinent.keySet()) {
        boolean hasStarted = started.get(string.toString()).booleanValue();
        if (hasStarted) {
            BufferedWriter bf = files.get(string.toString());
            bf.append("</rdf:RDF>");
            bf.flush();
            bf.close();
        }
    }
    return;
}

From source file:it.sayservice.platform.smartplanner.utils.LegGenerator.java

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

    Mongo m = new Mongo("localhost"); // default port 27017
    DB db = m.getDB("smart-planner-15x");
    DBCollection coll = db.getCollection("stops");

    // read trips.txt(trips,serviceId).
    List<String[]> trips = readFileGetLines("src/main/resources/schedules/17/trips.txt");
    List<String[]> stopTimes = readFileGetLines("src/main/resources/schedules/17/stop_times.txt");
    for (String[] words : trips) {
        try {//from  w  ww .j a  v  a 2s .  co  m
            String routeId = words[0].trim();
            String serviceId = words[1].trim();
            String tripId = words[2].trim();
            // fetch schedule for trips.
            for (int i = 0; i < stopTimes.size(); i++) {
                // already ordered by occurence.
                String[] scheduleLeg = stopTimes.get(i);
                if (scheduleLeg[0].equalsIgnoreCase(tripId)) {
                    // check if next leg belongs to same trip
                    if (stopTimes.get(i + 1)[0].equalsIgnoreCase(tripId)) {

                        String arrivalT = scheduleLeg[1];
                        String departT = scheduleLeg[2];
                        String sourceId = scheduleLeg[3];
                        String destId = stopTimes.get(i + 1)[3];
                        // get coordinates of stops.
                        /**
                         * make sure that mongo stop collection is
                         * populated. if, not, invoke
                         * http://localhost:7070/smart
                         * -planner/rest/getTransitTimes
                         * /TB_R2_R/1366776000000/1366819200000
                         */
                        Stop source = (Stop) getObjectByField(db, "id", sourceId, coll, Stop.class);
                        Stop destination = (Stop) getObjectByField(db, "id", destId, coll, Stop.class);
                        // System.out.println(tripId + ","
                        // + routeId + ","
                        // + source.getId() + ","
                        // + source.getLatitude() + ","
                        // + source.getLongitude() + ","
                        // + arrivalT + ","
                        // + destination.getId() + ","
                        // + destination.getLatitude() + ","
                        // + destination.getLongitude() + ","
                        // + departT + ","
                        // + serviceId
                        // );
                        String content = tripId + "," + routeId + "," + source.getStopId() + ","
                                + source.getLatitude() + "," + source.getLongitude() + "," + arrivalT + ","
                                + destination.getStopId() + "," + destination.getLatitude() + ","
                                + destination.getLongitude() + "," + departT + "," + "Giornaliero" + "\n";

                        File file = new File("src/main/resources/legs/legs.txt");
                        // single leg file
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(content);
                        bw.close();
                        // individual trip leg file.
                        File fileT = new File("src/main/resources/legs/legs_" + routeId + ".txt");
                        FileWriter fwT = new FileWriter(fileT.getAbsoluteFile(), true);
                        BufferedWriter bwT = new BufferedWriter(fwT);
                        bwT.write(content);
                        bwT.close();

                    }
                }
            }

        } catch (Exception e) {
            System.out.println("Error parsing trip: " + words[0] + "," + words[1] + "," + words[2]);
        }
    }
    System.out.println("Done");
}