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:ch.ethz.matsim.ivt_baseline.counts.StreetCountsLinkIdentification.java

private static void writeStreetCounts(String pathToCountsOutput, Map<CountInput, Id<Link>> identifiedLinks) {
    BufferedWriter writer = IOUtils.getBufferedWriter(pathToCountsOutput, Charset.forName("UTF-8"));
    try {//  ww  w .  j a  v  a 2s. c om
        String header = "countStationId" + COUNTS_DELIMITER + "direction" + COUNTS_DELIMITER + "linkId";
        writer.write(header);
        writer.newLine();
        //for (Id<Link> linkId : identifiedLinks.keySet()) {
        for (CountInput countInput : identifiedLinks.keySet()) {
            writer.write(countInput.id + COUNTS_DELIMITER);
            writer.write(countInput.directionDescr + COUNTS_DELIMITER);
            writer.write(identifiedLinks.get(countInput).toString());
            writer.newLine();
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.axelor.apps.tool.file.FileTool.java

/**
 * Mthode permettant d'crire plusieurs lignes dans un fichier
 * @param destinationFolder//from w w w.  jav a  2s.c o m
 *             Le chemin du fichier
 * @param fileName
 *             Le nom du fichier
 * @param line
 *             La liste de ligne  crire
 * @throws IOException
 */
public static void writer(String destinationFolder, String fileName, List<String> multiLine)
        throws IOException {
    System.setProperty("line.separator", "\r\n");
    BufferedWriter output = null;
    try {

        File file = create(destinationFolder, fileName);
        output = new BufferedWriter(new FileWriter(file));
        int i = 0;

        for (String line : multiLine) {

            output.write(line);
            output.newLine();
            i++;
            if (i % 50 == 0) {
                output.flush();
            }

        }

    } catch (IOException ex) {

        LOG.error(ex.getMessage());

    } finally {

        if (output != null) {
            output.close();
        }
    }
}

From source file:com.hp.test.framework.htmparse.HtmlParse.java

public static void replaceCountsinJSFile(File jsFile, String TargetPath) {

    try {//from w w  w  .j a va 2 s.c o  m
        String[] filename = jsFile.getName().split("/.");
        BufferedReader in = new BufferedReader(new FileReader(jsFile));
        BufferedWriter out = new BufferedWriter(new FileWriter(TargetPath + "\\" + filename[0]));

        String str;

        while ((str = in.readLine()) != null) {

            if (str.contains("AmCharts.ready")) {
                out.write(str);
                out.write("\n");
                out.write(HtmlParse.getCountsSuiteswise(TargetPath + "/CurrentRun.html"));

            } else {
                out.write(str);
                out.write("\n");
            }

        }
        in.close();
        out.close();
        System.out.println("Replacing Counts in .js file is done ");

        File amcharts = new File("HTML_Design_Files/JS/amcharts.js");
        File serial = new File("HTML_Design_Files/JS/serial.js");
        FileUtils.copyFile(amcharts, new File(TargetPath + "/amcharts.js"));
        FileUtils.copyFile(serial, new File(TargetPath + "/serial.js"));

    } catch (IOException e) {
        System.out.println("Exception in Replacing Counts in .js file is done " + e.getMessage());
    }

}

From source file:com.jbirdvegas.mgerrit.helpers.GerritTeamsHelper.java

private static void writeTeamToCache(String teamName, String teamUrl) {
    File teamPath = new File(mExternalCacheDir.getAbsolutePath() + '/' + teamName);
    if (teamPath.exists()) {
        teamPath.delete();//ww  w.  j  ava  2s .co  m
    }
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(teamPath));
        try {
            writer.write(new JSONObject().put(KEY_TEAM_NAME, teamName).put(KEY_TEAM_URL, teamUrl)
                    .put(KEY_TIMESTAMP, System.currentTimeMillis()).toString());
        } catch (JSONException e) {
            Log.e(TAG, "Failed to encode gerrit info to json", e);
        }
    } catch (IOException e) {
        Log.e(TAG, "Failed to write file to the cache", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                // let it go
            }
        }
    }
}

From source file:eu.smartfp7.foursquare.AttendanceCrawler.java

/**
 * From GitHub issue: https://github.com/SmartSearch/Foursquare-Attendance-Crawler/issues/3
 * /*from  ww w .j  av  a2s  .c  om*/
 * Venues can be deleted by/on Foursquare, resulting in errors when the crawler 
 * attempts to retrieve the hourly attendance. It also has bad consequences: the 
 * crawler tries to obtain the attendance over and over, draining the number of 
 * API calls, which also impacts the crawling of other venues and can lead to 
 * missing obervations.
 * 
 * This function removes a venue from the different files, so that it won't be
 * considered by the crawler anymore.
 */
public static void removeVenue(String venue_id, String city) {
    /**
     * First part: we need to remove `venue_id` from the ids file. We use a temporary
     * file to do this.
     */
    String ids_file = Settings.getInstance().getFolder() + city + File.separator + "venues.ids";
    String tmp_ids_file = Settings.getInstance().getFolder() + city + File.separator + "venues.ids.tmp";

    try {
        BufferedReader reader = new BufferedReader(new FileReader(ids_file));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tmp_ids_file));

        String line = null;

        while ((line = reader.readLine()) != null) {
            // Skipping `venue_id` when rewriting the file.
            String trimmedLine = line.trim();
            if (trimmedLine.equals(venue_id))
                continue;

            writer.write(line + "\n");
        }

        reader.close();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // When we have finished rewriting, we rename the temporary file so that it
    // becomes the real one.
    new File(tmp_ids_file).renameTo(new File(ids_file));

    /** End of first part. */

    /**
     * Second part: we need to delete the files related to the venue that have
     * been created while crawling (i.e. .ts and .info).
     * Instead, we move them into a .deleted folder that can allow us to recover
     * from hypothetical errors.
     */

    new File(Settings.getInstance().getFolder() + city + File.separator + "attendances_crawl" + File.separator
            + venue_id + ".ts")
                    .renameTo(new File(Settings.getInstance().getFolder() + city + File.separator + ".deleted"
                            + File.separator + venue_id + ".ts"));

    new File(Settings.getInstance().getFolder() + city + File.separator + "foursquare_venues" + File.separator
            + venue_id + ".info")
                    .renameTo(new File(Settings.getInstance().getFolder() + city + File.separator + ".deleted"
                            + File.separator + venue_id + ".info"));

    /** End of second part. */
}

From source file:com.bristle.javalib.io.FileUtil.java

/**************************************************************************
* Append the specified string to the specified file, opening and closing
* the file to do so./* ww  w.  j av a 2  s .c om*/
*@param  strFilename   String name of the file to get.
*@param  strString     String to append to the file.
*@throws IOException   When an error occurs writing the file.
**************************************************************************/
public static void appendToFile(String strFilename, String strString) throws IOException {
    final boolean blnAPPEND = true;
    BufferedWriter fileOut = new BufferedWriter(new FileWriter(strFilename, blnAPPEND));
    fileOut.write(strString);
    fileOut.close();
}

From source file:playground.johannes.socialnets.GraphStatistics.java

public static void writeHistogram(Histogram1D hist, String filename) {
    try {//from  w w  w . j  a  va 2  s.c o  m
        BufferedWriter writer = IOUtils.getBufferedWriter(filename);
        writer.write("x\ty");
        writer.newLine();
        for (int i = 0; i < 100; i++) {
            writer.write(String.valueOf(hist.xAxis().binCentre(i)));
            writer.write("\t");
            writer.write(String.valueOf(hist.binHeight(i)));
            writer.newLine();
        }
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.util.MalletUtils.java

public static void writeNewLineToFile(File outputFile) throws IOException {
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outputFile, true)), "UTF-8"));
    bw.write("\n");
    bw.flush();/*from   w w  w  .  j av a  2  s  .c om*/
    bw.close();
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java

public static void runonfileValidJson(String input_filename, String output_filename) throws IOException {
    InputStream fis;//w  ww.ja va  2 s  . co  m
    BufferedReader bufferdReader;
    String line;

    try {
        File file = new File(output_filename);
        if (file.createNewFile()) {
            logger.warn("File has been created");
        } //else {
          //   logger.info("File already exists.");
          //}
          // if (!file.getParentFile().mkdirs())
          // throw new IOException("Unable to create " +
          // file.getParentFile());

        FileWriter fileWriter = new FileWriter(output_filename, false);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        String parsedLine;
        fis = new FileInputStream(input_filename);
        bufferdReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
        while ((line = bufferdReader.readLine()) != null) {
            parsedLine = runOnStringJson(new Text(line), output_filename) + "\n";
            bufferedWriter.write(parsedLine);
        }
        bufferedWriter.close();
        bufferdReader.close();
    } catch (IOException e) {
        logger.error("Error writing to file '" + output_filename + "'");
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("Ouput written to " + output_filename);
}

From source file:LVCoref.MMAX2.java

/**
 * //from w  w  w  .j a va  2 s  .com
 * @param filename
 * @param path with trailing "/"
 */
public static void createProject(Document d, String project, String path) {
    String words = path + project + "_words.xml";
    String coref_level = path + project + "_coref_level.xml";
    String sentence_level = path + project + "_sentence_level.xml";
    String project_file = path + project + ".mmax";

    exportWords(d, words);
    exportMentions(d, coref_level);
    exportSentences(d, sentence_level);

    //-----Create project file
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(project_file), "UTF-8"));
    } catch (java.io.IOException ex) {
        ex.printStackTrace();
    }
    Utils.toWriter(writer,
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<mmax_project>\n" + "<words>" + project
                    + "_words.xml" + "</words>\n" + "<keyactions></keyactions>\n" + "<gestures></gestures>\n"
                    + "</mmax_project>\n");
    try {
        writer.flush();
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Document.class.getName()).log(Level.SEVERE, null, ex);
    }
}