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:com.normsstuff.maps4norm.Util.java

/**
 * Writes the given trace of points to the given file in CSV format,
 * separated by ";"//from w  w  w. jav  a2  s  . co  m
 *
 * @param f     the file to write to
 * @param trace the trace to write
 * @throws IOException
 */
static void saveToFile(final File f, final Stack<LatLng> trace) throws IOException {
    if (!f.exists())
        f.createNewFile();
    BufferedWriter out = new BufferedWriter(new FileWriter(f));
    LatLng current;
    for (int i = 0; i < trace.size(); i++) {
        current = trace.get(i);
        out.append(String.valueOf(current.latitude)).append(";").append(String.valueOf(current.longitude))
                .append("\n");
    }
    out.close();
}

From source file:edu.iu.kmeans.regroupallgather.KMUtil.java

/**
 * Generate centroids and upload to the cDir
 * //  w  w  w. j av a 2 s  .com
 * @param numCentroids
 * @param vectorSize
 * @param configuration
 * @param random
 * @param cenDir
 * @param fs
 * @throws IOException
 */
static void generateCentroids(int numCentroids, int vectorSize, Configuration configuration, Path cenDir,
        FileSystem fs) throws IOException {
    Random random = new Random();
    double[] data = null;
    if (fs.exists(cenDir))
        fs.delete(cenDir, true);
    if (!fs.mkdirs(cenDir)) {
        throw new IOException("Mkdirs failed to create " + cenDir.toString());
    }
    data = new double[numCentroids * vectorSize];
    for (int i = 0; i < data.length; i++) {
        // data[i] = 1000;
        data[i] = random.nextDouble() * 1000;
    }
    Path initClustersFile = new Path(cenDir, Constants.CENTROID_FILE_NAME);
    System.out.println("Generate centroid data." + initClustersFile.toString());
    FSDataOutputStream out = fs.create(initClustersFile, true);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
    for (int i = 0; i < data.length; i++) {
        if ((i % vectorSize) == (vectorSize - 1)) {
            bw.write(data[i] + "");
            bw.newLine();
        } else {
            bw.write(data[i] + " ");
        }
    }
    bw.flush();
    bw.close();
    System.out.println("Wrote centroids data to file");
}

From source file:dk.netarkivet.harvester.harvesting.frontier.FullFrontierReport.java

/**
 * Generates an Heritrix frontier report wrapper object by parsing the frontier report returned by the JMX
 * controller as a string.//from   ww  w  .  j a v a  2  s.c  o  m
 *
 * @param jobName the Heritrix job name
 * @param contentsAsString the text returned by the JMX call
 * @return the report wrapper object
 */
public static FullFrontierReport parseContentsAsString(String jobName, String contentsAsString) {

    FullFrontierReport report = new FullFrontierReport(jobName);

    // First dump this possibly huge string to a file
    File tmpDir = Settings.getFile(CommonSettings.CACHE_DIR);
    File tmpFile = new File(tmpDir, jobName + "-" + System.currentTimeMillis() + ".txt");
    try {
        tmpFile.createNewFile();
        BufferedWriter out = new BufferedWriter(new FileWriter(tmpFile));
        out.write(contentsAsString);
        out.close();
    } catch (IOException e) {
        LOG.error("Failed to create temporary file", e);
        return report;
    }

    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader(tmpFile));
    } catch (FileNotFoundException e) {
        LOG.error("Failed to read temporary file", e);
        return report;
    }

    try {
        String lineToken = br.readLine(); // Discard header line
        while ((lineToken = br.readLine()) != null) {
            report.addLine(new FrontierReportLine(lineToken));
        }

        br.close();
    } catch (IOException e) {
        LOG.warn("Failed to close reader", e);
    } catch (Throwable t) {
        LOG.error(t);
        t.printStackTrace(System.err);
    } finally {
        FileUtils.remove(tmpFile);
    }

    return report;
}

From source file:com.incapture.rapgen.output.OutputWriter.java

/**
 * Some files are composed of multiple templates. So the map passed in here is filename to template order to template.
 * E.g. "file.txt"->1->"some code" "file.txt"->2->"other code" and so on.
 *
 * @param rootFolder/*w  w w. ja  v a  2s .  co  m*/
 * @param pathToTemplate
 */
public static void writeMultiPartTemplates(String rootFolder,
        Map<String, Map<String, StringTemplate>> pathToTemplate) {
    // For each file, dump the templates
    for (Map.Entry<String, Map<String, StringTemplate>> entry : pathToTemplate.entrySet()) {
        File file = new File(rootFolder, entry.getKey());
        file.getParentFile().mkdirs();

        BufferedWriter bow = null;
        try {
            bow = new BufferedWriter(new FileWriter(file));
            Set<String> sections = entry.getValue().keySet();
            SortedSet<String> sorted = new TreeSet<String>();
            sorted.addAll(sections);
            for (String sec : sorted) {
                bow.write(entry.getValue().get(sec).toString());
                bow.newLine();
            }
            bow.close();
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } finally {
            if (bow != null) {
                try {
                    bow.close();
                } catch (IOException e) {
                    System.err.println("Error closing output stream: " + ExceptionToString.format(e));
                }
            }
        }
    }
}

From source file:eu.annocultor.common.Utils.java

public static void saveStringToFile(String string, String fileName) throws FileNotFoundException, IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
    out.append(string);// w ww. j a v  a 2s .  com
    out.close();
}

From source file:com.xtructure.xevolution.tool.impl.ReadPopulationsTool.java

private static void writeLatest(long latest) {
    try {/*from   w  ww . j  a  v  a 2  s.  co m*/
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(LATEST, false));
            out.write(Long.toString(latest));
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (IOException e) {
        // nothing
    }
}

From source file:com.calamp.services.kinesis.events.writer.CalAmpEventWriter.java

public static void genRandEventsToFile(String filePath, int numToGen) throws IOException {
    // Repeatedly send stock trades with a some milliseconds wait in between
    BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, false));
    for (int i = 0; i < numToGen; i++) {
        CalAmpEvent event = CalAmpEventGenerator.getRandomMessage();
        bw.write(event.toJsonAsString());
        bw.newLine();//  w  ww  .ja va 2 s. c o m
        //System.out.println( event.toJsonAsString() );
        //System.out.println( CalAmpEvent.fromJsonAsString(event.toJsonAsString()) );
    }
    if (bw != null) {
        bw.close();
    }
}

From source file:edu.umd.cs.findbugs.detect.LpUtil.java

public static void writerLog(Object... str) {
    BufferedWriter writer = null;
    try {/*from w  w w .j  a  v a2 s .co  m*/
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(new File("d:\\123000.txt"), true), UTF8.charset));
        for (Object temp : str) {
            writer.write(String.valueOf(temp));
            writer.write("\r\n");
        }
    } catch (Exception e) {
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:es.chatclient.styles.CssGenerator.java

private static File createCssFile(File f, String generatedText) {

    BufferedWriter writer = null;
    File outputFile = null;/*from   www. java  2 s . c  o m*/

    try {

        outputFile = new File(DIR_GENERATED_CSS + f.getName());
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "utf-8"));
        writer.write(generatedText);

    } catch (IOException ex) {
        System.err.println("Error generando css file:" + f.getName());

    } finally {

        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ex) {
                Logger.getLogger(CssGenerator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    return outputFile;
}

From source file:elh.eus.absa.NLPpipelineWrapper.java

public static int eustaggerCall(String taggerCommand, String string, String fname) {

    try {/*from w  ww .ja va  2s.  c o m*/
        File temp = new File(fname);
        //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath());
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write(string + "\n");
        bw.close();

        String[] command = { taggerCommand, temp.getName() };
        System.err.println("Eustagger agindua: " + Arrays.toString(command));

        ProcessBuilder eustBuilder = new ProcessBuilder().command(command);
        eustBuilder.directory(new File(temp.getParent()));
        //.redirectErrorStream(true);
        Process eustagger = eustBuilder.start();
        int success = eustagger.waitFor();
        //System.err.println("eustagger succesful? "+success);
        if (success != 0) {
            System.err.println("eustaggerCall: eustagger error");
        } else {
            String tagged = fname + ".kaf";
            BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream()));
            //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu
            if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) {
                Files.copy(eustagger.getInputStream(), Paths.get(tagged));
            }
            // old eustagger (euslem)
            else {
                FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged);
            }
        }
        //
        // delete all temporal files used in the process.
        temp.delete();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return -1;
    }

    return 0;
}