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:entity.files.SYSFilesTools.java

/**
 * Standard Druck Routine. Nimmt einen HTML Text entgegen und ffnet den lokal installierten Browser damit.
 * Erstellt temporre Dateien im temp Verzeichnis opde<irgendwas>.html
 *
 * @param html//from  w w  w  .  jav  a 2  s. c  o m
 * @param addPrintJScript Auf Wunsch kann an das HTML automatisch eine JScript Druckroutine angehangen werden.
 */
public static File print(String html, boolean addPrintJScript) {
    File temp = null;
    try {
        // Create temp file.
        temp = File.createTempFile("opde", ".html");

        String text = "<html><head>";
        if (addPrintJScript) {
            text += "<script type=\"text/javascript\">" + "window.onload = function() {" + "window.print();"
                    + "}</script>";
        }
        text += OPDE.getCSS();
        text += "</head><body>" + SYSTools.htmlUmlautConversion(html) + "<hr/>" + "<div id=\"fonttext\">"
                + "<b>" + SYSTools.xx("misc.msg.endofreport") + "</b><br/>"
                + (OPDE.getLogin() != null ? SYSTools.htmlUmlautConversion(OPDE.getLogin().getUser().getUID())
                        : "")
                + "<br/>" + DateFormat.getDateTimeInstance().format(new Date()) + "<br/>"
                + OPDE.getAppInfo().getProgname() + ", v" + OPDE.getAppInfo().getVersion() + "/"
                + OPDE.getAppInfo().getBuildnum() + "</div></body></html>";

        // Write to temp file
        BufferedWriter out = new BufferedWriter(new FileWriter(temp));
        out.write(text);

        out.close();
        SYSFilesTools.handleFile(temp, Desktop.Action.OPEN);
    } catch (IOException e) {
        OPDE.error(e);
    }
    return temp;
}

From source file:com.wavemaker.common.util.IOUtils.java

public static void write(File f, String s) throws IOException {
    f.getParentFile().mkdirs();//www .j a va 2 s  .c  o  m
    BufferedWriter br = null;
    try {
        br = new BufferedWriter(new FileWriter(f));
        br.write(s);
    } finally {
        try {
            br.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.wakatime.intellij.plugin.WakaTime.java

private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) {
    final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats);
    log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds)));
    try {/*from   www .j a va 2s .c om*/
        Process proc = Runtime.getRuntime().exec(cmds);
        if (extraHeartbeats.size() > 0) {
            String json = toJSON(extraHeartbeats);
            log.debug(json);
            try {
                BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
                stdin.write(json);
                stdin.write("\n");
                try {
                    stdin.flush();
                    stdin.close();
                } catch (IOException e) {
                    /* ignored because wakatime-cli closes pipe after receiving \n */ }
            } catch (IOException e) {
                log.warn(e);
            }
        }
        if (WakaTime.DEBUG) {
            BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            proc.waitFor();
            String s;
            while ((s = stdout.readLine()) != null) {
                log.debug(s);
            }
            while ((s = stderr.readLine()) != null) {
                log.debug(s);
            }
            log.debug("Command finished with return value: " + proc.exitValue());
        }
    } catch (Exception e) {
        log.warn(e);
    }
}

From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java

public static void saveDefaultChart(Chart chart) {
    Log logger = LogFactory.getLog(ChartsPlugin.class);
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$

    try {/*from ww w .  j  a  va  2  s . c  o m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        Element node = document.createElement("title"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(chart.getTitle()));
        root.appendChild(node);
        node = document.createElement("compression"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
        root.appendChild(node);
        node = document.createElement("period"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
        root.appendChild(node);
        node = document.createElement("autoScale"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
        root.appendChild(node);
        if (chart.getBeginDate() != null) {
            node = document.createElement("begin"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
            root.appendChild(node);
        }
        if (chart.getEndDate() != null) {
            node = document.createElement("end"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
            root.appendChild(node);
        }
        for (int r = 0; r < chart.getRows().size(); r++) {
            ChartRow row = (ChartRow) chart.getRows().get(r);
            row.setId(new Integer(r));

            Element rowNode = document.createElement("row"); //$NON-NLS-1$
            root.appendChild(rowNode);

            for (int t = 0; t < row.getTabs().size(); t++) {
                ChartTab tab = (ChartTab) row.getTabs().get(t);
                tab.setId(new Integer(t));

                Element tabNode = document.createElement("tab"); //$NON-NLS-1$
                tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
                rowNode.appendChild(tabNode);

                for (int i = 0; i < tab.getIndicators().size(); i++) {
                    ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                    indicator.setId(new Integer(i));

                    Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }

                for (int i = 0; i < tab.getObjects().size(); i++) {
                    ChartObject object = (ChartObject) tab.getObjects().get(i);
                    object.setId(new Integer(i));

                    Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }
            }
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();

    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
}

From source file:com.hp.test.framework.Reporting.removerunlinks.java

public static void removelinksforpreRuns(String FilePath, String FileName, int lastrun)
        throws FileNotFoundException, IOException {

    log.info("Removing hyper link for the last run");
    ArrayList<String> Links_To_Remove = new ArrayList<String>();

    for (int i = 1; i < lastrun; i++) {
        Links_To_Remove.add("href=\"Run_" + i + "\\CurrentRun.html\"");
    }/* w  w  w  .  j ava 2 s  .c o m*/

    File source = new File(FilePath + FileName);
    File temp_file = new File(FilePath + "temp.html");
    BufferedReader in = new BufferedReader(new FileReader(source));
    BufferedWriter out = new BufferedWriter(new FileWriter(temp_file));
    String str = "";
    while ((str = in.readLine()) != null) {

        String temp_ar[] = str.split(" ");

        for (int i = 0; i < temp_ar.length; i++) {
            String temp = temp_ar[i].trim();
            if (!temp.equals("")) {

                if (Links_To_Remove.contains(temp)) {
                    out.write(" ");
                    out.newLine();

                } else {
                    out.write(temp);
                    out.newLine();

                }

            }
        }
    }

    out.close();
    in.close();
    out = null;
    in = null;

    source.delete();
    temp_file.renameTo(source);

}

From source file:atg.tools.dynunit.test.util.FileUtil.java

/**
 * @see #forceGlobalScope(java.io.File)/*from   w  w w. j  a v  a 2 s. c o  m*/
 * @see #forceComponentScope(java.io.File, String)
 */
@Deprecated
public static void searchAndReplace(@NotNull final String originalValue, @NotNull final String newValue,
        @NotNull final File file) throws IOException {
    final File tempFile = newTempFile();

    if (CONFIG_FILES_GLOBAL_FORCE != null && CONFIG_FILES_GLOBAL_FORCE.get(file.getPath()) != null
            && CONFIG_FILES_GLOBAL_FORCE.get(file.getPath()) == file.lastModified() && file.exists()) {
        dirty = false;
        logger.debug(
                "{} last modified hasn't changed and file still exists, " + "no need for global scope force",
                file.getPath());
    } else {
        final BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
        final BufferedReader in = new BufferedReader(new FileReader(file));
        String str;
        while ((str = in.readLine()) != null) {
            if (str.contains(originalValue)) {
                out.write(newValue);
            } else {
                out.write(str);
                out.newLine();
            }
        }
        out.close();
        in.close();
        JarUtils.copy(tempFile, file, true, false);
        CONFIG_FILES_GLOBAL_FORCE.put(file.getPath(), file.lastModified());
        dirty = true;
    }

}

From source file:de.uzk.hki.da.metadata.XmpCollector.java

/**
 * Collect.//w w  w .j a v a 2  s.c om
 *
 * @param xmpFiles list of xmp files to collect
 * @param targetFile the target file
 * @throws IOException 
 */
public static void collect(WorkArea wa, List<DAFile> xmpFiles, File targetFile) throws IOException {

    Model model = ModelFactory.createDefaultModel();

    for (DAFile dafile : xmpFiles) {

        File file = wa.toFile(dafile);

        logger.debug("collecting XMP file {}", file.getAbsolutePath());

        StringWriter xmpWriter = new StringWriter();

        try {
            // preprocess xmp in order to make it RDF/XML compatible   
            BufferedReader reader = new BufferedReader(new FileReader(file));
            BufferedWriter writer = new BufferedWriter(xmpWriter);

            logger.debug("Read the xmp file...");
            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                String trimmedLine = currentLine.trim();
                if (trimmedLine.startsWith("<?xpacket"))
                    continue;
                if (trimmedLine.contains("x:xmpmeta"))
                    continue;
                writer.write(currentLine);
            }
            reader.close();
            writer.close();

        } catch (Exception e) {
            throw new RuntimeException("Unable to preprocess XMP file: " + file.getAbsolutePath(), e);
        }

        final String baseName = FilenameUtils.removeExtension(file.getName());
        String[] list = file.getParentFile().list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                String baseName2 = FilenameUtils.removeExtension(name);
                if (baseName.equals(baseName2) && !name.toLowerCase().endsWith(".xmp"))
                    return true;
                else
                    return false;
            }
        });
        if (list.length > 1) {
            logger.warn("More than one matching file for sidecar file {}. Skipping ...", file.getName());
            continue;
        } else if (list.length < 1) {
            logger.warn("No matching file for sidecar file {}. Skipping ...", file.getName());
            continue;
        }

        logger.debug("found matching file {}", list[0]);
        // read XMP with matching file as base name
        // use "http://www.danrw.de/temp/" as a pseudo base URI in order to allow relative resource URIs
        model.read(new StringReader(xmpWriter.toString().trim().replaceFirst("^([\\W]+)<", "<")),
                "http://www.danrw.de/temp/" + list[0]);
    }
    FileOutputStream targetStream = null;
    try {
        targetStream = new FileOutputStream(targetFile);
        model.write(targetStream, "RDF/XML-ABBREV", "http://www.danrw.de/temp/");
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Could not write XMP collection file: " + targetFile.getAbsolutePath());
    } finally {
        if (targetStream != null) {
            targetStream.close();
        }
    }

}

From source file:com.iitb.cse.ConnectionInfo.java

public static void writeToMyLog(int expid, String macAdrress, String message) {

    String location = "";

    if (!Constants.experimentDetailsDirectory.endsWith("/")) {
        location = Constants.experimentDetailsDirectory + "/";
    }//from  w  w w  .jav a2s  .  c  om

    location += Integer.toString(expid) + macAdrress + "_log.txt";
    File file = new File(location);
    try {
        FileWriter fw = new FileWriter(file, true);
        BufferedWriter bw = new BufferedWriter(fw);
        Date date = new Date();
        System.out.println(date);
        bw.write(date.toString() + " --> " + message + "\n");
        bw.close();
    } catch (IOException ex) {
        System.out.println("\nEXCEPTION [writeToMyLog]:" + ex.toString());
    }
}

From source file:com.ibm.bi.dml.runtime.util.MapReduceTool.java

public static void writeDoubleToHDFS(double d, String filename) throws IOException {
    BufferedWriter br = setupOutputFile(filename);
    String line = "" + d;
    br.write(line);// www .j a va 2s  .co m
    br.close();
}

From source file:com.ibm.bi.dml.runtime.util.MapReduceTool.java

public static void writeIntToHDFS(long i, String filename) throws IOException {
    BufferedWriter br = setupOutputFile(filename);
    String line = "" + i;
    br.write(line);// ww w . ja va 2 s  .co  m
    br.close();
}