Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:Main.java

public static void copyCompletely(Reader input, Writer output) throws IOException {
    char[] buf = new char[8192];
    while (true) {
        int length = input.read(buf);
        if (length < 0)
            break;
        output.write(buf, 0, length);/* w  ww .  ja v a 2 s  .  c  om*/
    }

    try {
        input.close();
    } catch (IOException ignore) {
    }
    try {
        output.close();
    } catch (IOException ignore) {
    }
}

From source file:com.discovery.darchrow.io.IOWriteUtil.java

/**
 * ./*from w  ww  .  j a  v  a  2s  .c o m*/
 * 
 * <ul>
 * <li>?,, (?? )</li>
 * <li>,?  {@link FileWriteMode#APPEND}??</li>
 * </ul>
 *
 * @param filePath
 *            
 * @param content
 *            
 * @param encode
 *            ?,isNullOrEmpty, {@link CharsetType#GBK}? {@link CharsetType}
 * @param fileWriteMode
 *            ?
 * @see FileWriteMode
 * @see CharsetType
 * @see java.io.FileOutputStream#FileOutputStream(File, boolean)
 */
public static void write(String filePath, String content, String encode, FileWriteMode fileWriteMode) {

    //TODO ? ???? 
    if (Validator.isNullOrEmpty(encode)) {
        encode = CharsetType.GBK;
    }

    // **************************************************************************8
    File file = new File(filePath);

    FileUtil.createDirectoryByFilePath(filePath);

    OutputStream outputStream = null;
    try {
        outputStream = FileUtil.getFileOutputStream(filePath, fileWriteMode);
        //TODO ? write(inputStream, outputStream);

        Writer outputStreamWriter = new OutputStreamWriter(outputStream, encode);

        Writer writer = new PrintWriter(outputStreamWriter);
        writer.write(content);
        writer.close();

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("fileWriteMode:[{}],encode:[{}],contentLength:[{}],fileSize:[{}],absolutePath:[{}]",
                    fileWriteMode, encode, content.length(), FileUtil.getFileFormatSize(file),
                    file.getAbsolutePath());
        }
        outputStream.close();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.ibm.jaggr.core.util.CopyUtil.java

public static void copy(String str, Writer writer) throws IOException {
    Reader reader = new StringReader(str);
    try {//from   ww w.  j  av  a  2  s . co  m
        IOUtils.copy(reader, writer);
    } finally {
        try {
            reader.close();
        } catch (Exception ignore) {
        }
        try {
            writer.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:Main.java

public static String highlight(final List<String> lines, final String meta, final String prog,
        final String encoding) throws IOException {
    final File tmpIn = new File(System.getProperty("java.io.tmpdir"),
            String.format("txtmark_code_%d_%d.in", ID, IN_COUNT.incrementAndGet()));
    final File tmpOut = new File(System.getProperty("java.io.tmpdir"),
            String.format("txtmark_code_%d_%d.out", ID, OUT_COUNT.incrementAndGet()));

    try {//from   w ww . j  a va  2s .com

        final Writer w = new OutputStreamWriter(new FileOutputStream(tmpIn), encoding);

        try {
            for (final String s : lines) {
                w.write(s);
                w.write('\n');
            }
        } finally {
            w.close();
        }

        final List<String> command = new ArrayList<String>();

        command.add(prog);
        command.add(meta);
        command.add(tmpIn.getAbsolutePath());
        command.add(tmpOut.getAbsolutePath());

        final ProcessBuilder pb = new ProcessBuilder(command);
        final Process p = pb.start();
        final InputStream pIn = p.getInputStream();
        final byte[] buffer = new byte[2048];

        int exitCode = 0;
        for (;;) {
            if (pIn.available() > 0) {
                pIn.read(buffer);
            }
            try {
                exitCode = p.exitValue();
            } catch (final IllegalThreadStateException itse) {
                continue;
            }
            break;
        }

        if (exitCode == 0) {
            final Reader r = new InputStreamReader(new FileInputStream(tmpOut), encoding);
            try {
                final StringBuilder sb = new StringBuilder();
                for (;;) {
                    final int c = r.read();
                    if (c >= 0) {
                        sb.append((char) c);
                    } else {
                        break;
                    }
                }
                return sb.toString();
            } finally {
                r.close();
            }
        }

        throw new IOException("Exited with exit code: " + exitCode);
    } finally {
        tmpIn.delete();
        tmpOut.delete();
    }
}

From source file:com.schnobosoft.semeval.cortical.SemEvalTextSimilarity.java

/**
 * Save the values for the metrics using all measures defined in {@link Measure}. All values
 * are scaled to the range [0,5]./*  w w  w .  j  av a2s  .  c  om*/
 *
 * @param metrics   a list of {@link Metric}s
 * @param inputFile the input file, used for specifying the output files
 * @throws IOException
 */
private static void saveScores(Metric[] metrics, File inputFile, Retina retinaName) throws IOException {
    for (Measure measure : Measure.values()) {
        File outputFile = getOutputFile(inputFile, measure, retinaName);
        Writer writer = new BufferedWriter(new FileWriter(outputFile));

        List<Double> scores = Util.scale(Util.getScores(metrics, measure), measure);

        LOG.info("Writing output for '" + inputFile + "'.");
        for (Double score : scores) {
            writer.write(String.valueOf(score) + "\n");
        }
        writer.close();
    }
}

From source file:gdv.xport.util.AbstractFormatterTest.java

/**
 * Verwendet {@link AbstractFormatter#notice(gdv.xport.satz.Satz)} fuer
 * den Export und ueberprueft das Ergebnis mit einer bereits exportierten
 * Datei./* w  w w  .j  a va2 s  . c o  m*/
 *
 * @param formatter the formatter
 * @param filename the filename
 * @throws IOException falls was schiefgelaufen ist
 */
protected static void checkNotice(final AbstractFormatter formatter, final String filename) throws IOException {
    File output = File.createTempFile("test-notice", ".export");
    Writer writer = new OutputStreamWriter(new FileOutputStream(output), "ISO-8859-1");
    formatter.setWriter(writer);
    try {
        exportMusterdatei(formatter);
        log.info("Musterdatei was exported to " + output);
    } finally {
        writer.close();
        output.deleteOnExit();
    }
    File exported = new File("target/site", filename);
    if (exported.exists()) {
        log.info(output + " will be compared with already generated " + exported);
        FileTester.assertContentEquals(exported, output, Charset.forName("ISO-8859-1"),
                Pattern.compile("<!--.*-->"));
    }
}

From source file:com.ibm.jaggr.core.util.CopyUtil.java

public static void copy(InputStream in, Writer writer) throws IOException {
    Reader reader = new InputStreamReader(in, "UTF-8"); //$NON-NLS-1$
    try {/*from ww w  .  j  a  va 2 s  .  c o  m*/
        IOUtils.copy(reader, writer);
    } finally {
        try {
            reader.close();
        } catch (Exception ignore) {
        }
        try {
            writer.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.dajodi.scandic.Util.java

public static void writeMemberInfo(Context context, MemberInfo memberInfo) throws IOException {

    PersistedData data = new PersistedData();
    data.setMemberInfo(memberInfo);/*from  w  ww  .jav  a  2  s.com*/

    File f = context.getFilesDir();
    Writer writer = new BufferedWriter(new FileWriter(new File(f, JSON_FILENAME)));
    try {
        new JSONSerializer().deepSerialize(data, writer);
        writer.flush();
    } finally {
        writer.close();
    }
}

From source file:jo.alexa.sim.ui.logic.RuntimeLogic.java

public static void saveHistory(RuntimeBean runtime, File source) throws IOException {
    JSONArray transs = ToJSONLogic.toJSONTransactions(runtime.getHistory());
    OutputStream os = new FileOutputStream(source);
    Writer wtr = new OutputStreamWriter(os, "utf-8");
    wtr.write(transs.toJSONString());/*from  w w w. j av a 2  s.c om*/
    wtr.close();
    setProp("app.history", source.toString());
}

From source file:com.twentyn.patentExtractor.Util.java

public static byte[] compressXMLDocument(Document doc)
        throws IOException, TransformerConfigurationException, TransformerException {
    Transformer transformer = getTransformerFactory().newTransformer();
    // The OutputKeys.INDENT configuration key determines whether the output is indented.

    DOMSource w3DomSource = new DOMSource(doc);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer w = new BufferedWriter(new OutputStreamWriter(
            new GZIPOutputStream(new Base64OutputStream(baos, true, 0, new byte[] { '\n' }))));
    StreamResult sResult = new StreamResult(w);
    transformer.transform(w3DomSource, sResult);
    w.close();
    return baos.toByteArray();
}