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.orange.atk.results.logger.documentGenerator.GraphGenerator.java

/**
 * Save the data of a plot list into a file. A divisor value coould be apply
 * to X, ie values would be dived by Xdivisor value are
 * stored on each line as :<br/> (x_i-x_0)/Xdivisor \t y <br/>
 * format, the first value is shifted to 0.
 * /*from w w w  . j a va2 s  .co  m*/
 * @param plotList
 *            plot list to save
 * @param fileName
 *            file name where plot list would be saved
 * @param Xdivisor
 *            divisor for the X axis
 * @param Ydivisor
 *            divisor for the Y axis
 * @throws ArrayIndexOutOfBoundsException
 * @throws IOException
 */
public static void dumpInFile(PlotList plotList, String fileName)
        throws ArrayIndexOutOfBoundsException, IOException {
    int iXListSize = plotList.getSize();
    if (iXListSize > 0) {
        // get the first value to translate the x scale
        // x rep
        SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        SimpleDateFormat year = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat ms = new SimpleDateFormat("SSS");

        //      double initialValue = ((Long) plotList.getX(0)).doubleValue();
        File fichier = new File(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(fichier)));
        bufferedWriter.write("# " + spf.format(new Date(plotList.getX(0))) + "-" + Platform.LINE_SEP);
        bufferedWriter.write("# yyyy-MM-dd, HH:mm:ss:SSS,value" + Platform.LINE_SEP);
        for (int i = 0; i < iXListSize; i++) {
            // Logger.getLogger(this.getClass() ).debug(((plotList.getX(i)).floatValue()) + " - "
            // + initialValue);
            long xval = (((Long) plotList.getX(i)));
            float yval = plotList.getY(i).floatValue();
            bufferedWriter.write(year.format(new Date(xval)) + ", " + hour.format(new Date(xval)) + ":"
                    + ms.format(new Date(xval)) + "," + yval + Platform.LINE_SEP);

            // Logger.getLogger(this.getClass() ).debug(xval + "\t" + yval );
        }
        bufferedWriter.close();
    }
}

From source file:de.Keyle.MyPet.util.configuration.ConfigurationJSON.java

public boolean save() {
    try {/*from w  ww.  java  2  s .c o  m*/
        // http://jsonformatter.curiousconcept.com/
        BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));
        writer.write(config.toJSONString());
        writer.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        DebugLogger.printThrowable(e);
        return false;
    }
}

From source file:URLEncoder.java

public static String encode(String s, String enc) throws UnsupportedEncodingException {
    if (!needsEncoding(s)) {
        return s;
    }//from  ww w.j a v a 2s . c o m

    int length = s.length();

    StringBuffer out = new StringBuffer(length);

    ByteArrayOutputStream buf = new ByteArrayOutputStream(10); // why 10?
    // w3c says
    // so.

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(buf, enc));

    for (int i = 0; i < length; i++) {
        int c = (int) s.charAt(i);
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ' ') {
            if (c == ' ') {
                c = '+';
            }

            toHex(out, buf.toByteArray());
            buf.reset();

            out.append((char) c);
        } else {
            try {
                writer.write(c);

                if (c >= 0xD800 && c <= 0xDBFF && i < length - 1) {
                    int d = (int) s.charAt(i + 1);
                    if (d >= 0xDC00 && d <= 0xDFFF) {
                        writer.write(d);
                        i++;
                    }
                }

                writer.flush();
            } catch (IOException ex) {
                throw new IllegalArgumentException(s);
            }
        }
    }
    try {
        writer.close();
    } catch (IOException ioe) {
        // Ignore exceptions on close.
    }

    toHex(out, buf.toByteArray());

    return out.toString();
}

From source file:com.github.marabou.properties.PropertiesLoader.java

private void writeUserProperties(Properties userProperties) throws IOException {
    BufferedWriter userConf = createWriter(pathHelper.getUserPropertiesFilePath());
    userProperties.store(userConf, null);
    userConf.flush();/*from  w w w.j  av a 2  s.  c  o m*/
    userConf.close();
}

From source file:com.khepry.utilities.GenericUtilities.java

public static void displayLogFile(String logFilePath, long logSleepMillis, String xsltFilePath,
        String xsldFilePath) {//from   ww w .  j a v  a 2 s .  c o m
    Logger.getLogger("").getHandlers()[0].close();
    // only display the log file
    // if the logSleepMillis property
    // is greater than zero milliseconds
    if (logSleepMillis > 0) {
        try {
            Thread.sleep(logSleepMillis);
            File logFile = new File(logFilePath);
            File xsltFile = new File(xsltFilePath);
            File xsldFile = new File(xsldFilePath);
            File tmpFile = File.createTempFile("tmpLogFile", ".xhtml", logFile.getParentFile());
            if (logFile.exists()) {
                if (xsltFile.exists() && xsldFile.exists()) {
                    String xslFilePath;
                    String xslFileName;
                    String dtdFilePath;
                    String dtdFileName;
                    try {
                        xslFileName = new File(logFilePath).getName().replace(".xhtml", ".xsl");
                        xslFilePath = logFile.getParentFile().toString().concat("/").concat(xslFileName);
                        FileUtils.copyFile(new File(xsltFilePath), new File(xslFilePath));
                        dtdFileName = new File(logFilePath).getName().replace(".xhtml", ".dtd");
                        dtdFilePath = logFile.getParentFile().toString().concat("/").concat(dtdFileName);
                        FileUtils.copyFile(new File(xsldFilePath), new File(dtdFilePath));
                    } catch (IOException ex) {
                        String message = Level.SEVERE.toString().concat(": ").concat(ex.getLocalizedMessage());
                        Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, message, ex);
                        GenericUtilities.outputToSystemErr(message, logSleepMillis > 0);
                        return;
                    }
                    BufferedWriter bw = Files.newBufferedWriter(Paths.get(tmpFile.getAbsolutePath()),
                            Charset.defaultCharset(), StandardOpenOption.CREATE);
                    List<String> logLines = Files.readAllLines(Paths.get(logFilePath),
                            Charset.defaultCharset());
                    for (String line : logLines) {
                        if (line.startsWith("<!DOCTYPE log SYSTEM \"logger.dtd\">")) {
                            bw.write("<!DOCTYPE log SYSTEM \"" + dtdFileName + "\">\n");
                            bw.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslFileName + "\"?>\n");
                        } else {
                            bw.write(line.concat("\n"));
                        }
                    }
                    bw.write("</log>\n");
                    bw.close();
                }
                // the following statement is commented out because it's not quite ready for prime-time yet
                // Files.write(Paths.get(logFilePath), transformLogViaXSLT(logFilePath, xsltFilePath).getBytes(), StandardOpenOption.CREATE);
                Desktop.getDesktop().open(tmpFile);
            } else {
                Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, logFilePath,
                        new FileNotFoundException());
            }
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:net.librec.util.FileUtil.java

/**
 * Write contents in {@code List<T>} to a file with the help of a writer helper.
 *
 * @param filePath path of the file to write
 * @param ts       content to write/*from   w  w  w.  jav a2  s .  co m*/
 * @param wh       writer helper
 * @param append   whether to append
 * @param <T>      the type parameter
 * @throws Exception if error occurs
 */
public static <T> void writeVector(String filePath, List<T> ts, Converter<T, String> wh, boolean append)
        throws Exception {
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(filePath, append), "UTF-8"));
    int i = 0;
    StringBuilder sb = new StringBuilder();
    for (T t : ts) {
        sb.append(wh.transform(t));
        if (++i < ts.size())
            sb.append(", ");
    }
    bw.write(sb.toString() + "\n");
    bw.close();
}

From source file:ark.data.annotation.Document.java

public boolean saveToJSONFile(String path) {
    try {//from w  w w  .  j a va 2s.c  o m
        BufferedWriter w = new BufferedWriter(new FileWriter(path));

        w.write(toJSON().toString());

        w.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.mindcognition.mindraider.install.Installer.java

/**
 * Fix URIs - remove dvorka & savant in order to replace it with user's
 * hostname./* w w  w.j a v  a 2  s .c  o  m*/
 * 
 * @param filename
 *            the filename
 * @todo replace reading/closing file with commons-io functions
 */
public static void fixUris(String filename) {
    StringBuffer stringBuffer = new StringBuffer();
    BufferedReader in = null;
    try {

        // try to start reading
        in = new BufferedReader(new FileReader(new File(filename)));
        String line;
        while ((line = in.readLine()) != null) {
            stringBuffer.append(line);
            stringBuffer.append("\n");
        }
    } catch (IOException e) {
        logger.debug(Messages.getString("Installer.unableToReadFile", filename), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e1) {
                logger.debug(Messages.getString("Installer.unableToCloseReader"));
            }
        }
    }

    // file successfuly loaded - now replace strings
    String old = stringBuffer.toString();
    if (old != null) {
        String replacement = "http://" + profileHostname + "/e-mentality/mindmap#" + profileUsername;
        old = old.replaceAll("http://dvorka/e-mentality/mindmap#dvorka", replacement);
        old = old.replaceAll("http://dvorka/", "http://" + profileHostname + "/");
        old = old.replaceAll("http://savant/", "http://" + profileHostname + "/");
        // logger.debug(old+"\n");
    }

    // write it back
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter(filename));
        out.write(old);
    } catch (Exception e) {
        logger.debug(Messages.getString("Installer.unableToWriteFixedFile", filename), e);
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e1) {
                logger.debug(Messages.getString("Installer.unableToCloseFile", filename), e1);
            }
        }
    }
}

From source file:edu.utah.bmi.ibiomes.lite.ExperimentIndex.java

/**
 * Remove all entries/*from  w  w w. jav  a2 s  .  com*/
 * @throws IOException 
 */
public void clearAll() throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter(this.file, false));
    bw.write("");
    bw.close();
}

From source file:com.atlassian.clover.reporters.html.HtmlReporter.java

public static String renderHtmlBarTable(float pcCovered, int width, String customClass,
        String customBarPositive, String customBarNegative) throws Exception {

    final VelocityContext context = new VelocityContext();
    context.put("empty", Boolean.valueOf(pcCovered < 0));
    context.put("pccovered", new Float(pcCovered));
    context.put("sortValue", new Float(pcCovered));
    context.put("width", new Integer(width));
    context.put("customClass", customClass);
    context.put("customBarPositive", customBarPositive);
    context.put("customBarNegative", customBarNegative);
    context.put("renderUtil", new HtmlRenderingSupportImpl());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(baos, "UTF-8"));
    HtmlReportUtil.getVelocityEngine().mergeTemplate(HtmlReportUtil.getTemplatePath("bar-graph.vm"), "ASCII",
            context, out);//  w w  w .j  a v a 2s  .c om

    out.close();
    return baos.toString();
}