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:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

private static void writeAccessToken(JSONObject obj) {
    Writer writer = null;
    try {// w  w  w  .  ja  va2  s . com
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(tokenFilename), StandardCharsets.UTF_8));
        obj.writeJSONString(writer);

    } catch (IOException e) {
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

private static void textError(final ActiveCall call, final int status, final String message)
        throws IOException {
    final HttpServletResponse r = call.httpResponse;
    r.setStatus(status);// w w w .  jav  a 2 s. co m
    r.setContentType("text/plain; charset=" + ENC);

    final Writer w = new OutputStreamWriter(r.getOutputStream(), ENC);
    try {
        w.write(message);
    } finally {
        w.close();
    }
}

From source file:ca.licef.lompad.Classification.java

public static File doImportFile(Component parent) {
    JFileChooser chooser = new JFileChooser();
    if (Preferences.getInstance().getPrevClassifDir() != null)
        chooser.setCurrentDirectory(Preferences.getInstance().getPrevClassifDir());
    int returnVal = chooser.showOpenDialog(parent);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {/*from   w w  w.  j ava  2  s .c  o  m*/
            Preferences.getInstance().setPrevClassifDir(chooser.getCurrentDirectory());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            File skosInputFile = chooser.getSelectedFile();
            File tmpFile = null;

            String xml = IOUtil.readStringFromFile(chooser.getSelectedFile());
            String rootTagName = XMLUtil.getRootTagName(xml);
            if (rootTagName != null) {
                String[] array = StringUtil.split(rootTagName, ':');
                rootTagName = array[array.length - 1].toLowerCase();
            }
            boolean isVdexFile = (rootTagName != null && "vdex".equals(rootTagName));
            if (isVdexFile) {
                String xsltFile = "/xslt/convertVDEXToSKOS.xsl";
                StreamSource xslt = new StreamSource(Util.class.getResourceAsStream(xsltFile));

                StreamSource xmlSource = new StreamSource(new BufferedReader(new StringReader(xml)));

                Node skosNode = XMLUtil.applyXslToDocument2(xslt, xmlSource, null, null, null);
                tmpFile = File.createTempFile("lompad", "inputSkos");
                Writer tmpFileWriter = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(tmpFile, false), "UTF-8"));

                try {
                    XMLUtil.serialize(skosNode, false, tmpFileWriter);
                } finally {
                    if (tmpFileWriter != null)
                        tmpFileWriter.close();
                }
                skosInputFile = tmpFile;
            }

            Classification classif = new Classification(skosInputFile);
            classif.initModel(true);
            String uri = classif.getConceptSchemeUri();
            if (uri == null)
                throw new Exception("ConceptScheme's URI not found.");
            String sha1 = DigestUtils.shaHex(uri);
            File localFile = new File(Util.getClassificationFolder(), sha1 + ".rdf");
            classif.dumpModelToRdf(localFile);

            if (tmpFile != null)
                tmpFile.delete();

            return (localFile);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "classifImportFailed";
            if ("Classification identifier not found.".equals(e.getMessage()))
                msg = "classifIdentifierNotFound";
            JDialogAlert dialog = new JDialogAlert(Util.getTopJFrame((Container) parent), "titleErr", msg);
            dialog.setSize(320, 140);
            dialog.setVisible(true);
            return (null);
        }
    } else
        return (null);
}

From source file:com.twitter.elephanttwin.util.HdfsUtils.java

/**
 * Write \n separated lines of text to HDFS as UTF-8.
 *//*  w  ww. j  a v  a 2 s.  c  o  m*/
public static void writeLines(FileSystem fs, Path path, Iterable<String> lines) throws IOException {
    Preconditions.checkNotNull(fs);
    Preconditions.checkNotNull(path);
    Preconditions.checkNotNull(lines);
    Writer stream = new BufferedWriter(new OutputStreamWriter(fs.create(path), "UTF-8"));
    try {
        for (String line : lines) {
            stream.write(line + "\n");
        }
    } finally {
        stream.close();
    }
}

From source file:com.hazelcast.stabilizer.Utils.java

public static void writeText(String text, File file) {
    if (text == null) {
        throw new NullPointerException("text can't be null");
    }/*from   w  w  w. j av a2  s  .co  m*/

    if (file == null) {
        throw new NullPointerException("file can't be null");
    }

    try {
        FileOutputStream stream = new FileOutputStream(file);
        try {
            Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
            writer.write(text);
            writer.close();
        } finally {
            closeQuietly(stream);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hazelcast.stabilizer.Utils.java

public static void appendText(String text, File file) {
    if (text == null) {
        throw new NullPointerException("text can't be null");
    }/* w ww  .ja  v  a 2  s  . co  m*/

    if (file == null) {
        throw new NullPointerException("file can't be null");
    }

    try {
        FileOutputStream stream = new FileOutputStream(file, true);
        try {
            Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
            writer.write(text);
            writer.close();
        } finally {
            closeQuietly(stream);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when
 * finished.//from w w w  . j  a  v  a  2  s .co  m
 * 
 * @param content the content to write to the writer; may be null
 * @param writer the writer to which the content is to be written
 * @throws IOException
 * @throws IllegalArgumentException if the writer is null
 */
public static void write(String content, Writer writer) throws IOException {
    boolean error = false;
    try {
        if (content != null) {
            writer.write(content);
        }
    } catch (IOException e) {
        error = true; // this error should be thrown, even if there is an error flushing/closing writer
        throw e;
    } catch (RuntimeException e) {
        error = true; // this error should be thrown, even if there is an error flushing/closing writer
        throw e;
    } finally {
        try {
            writer.flush();
        } catch (IOException e) {
            if (!error)
                throw e;
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                if (!error)
                    throw e;
            }
        }
    }
}

From source file:com.sshtools.common.vomanagementtool.common.VOHelper.java

private static void appendLineToFavourites(String line) throws IOException {
    Writer output;
    output = new BufferedWriter(new FileWriter(favouritesFile, true));
    output.append(line + "\n");
    output.close();
}

From source file:mitm.common.extractor.impl.TextExtractorUtils.java

/**
 * conveniance method that writes data and fires a 
 * {@link TextExtractorEventHandler#textEvent(mitm.common.extractor.ExtractedPart)} event. The Data is written
 * to disk if total bytes exceed threshold. If total bytes written exceeds maxSize, an IOException will
 * be thrown.//  w ww  .  j  av  a  2s . co  m
 * 
 */
public static void fireTextEvent(TextExtractorEventHandler handler, TextExtractorContext context,
        TextExtractorWriterHandler writerHandler, int threshold, long maxSize) throws IOException {
    Check.notNull(handler, "handler");
    Check.notNull(writerHandler, "writerHandler");

    DeferredFileOutputStream output = new DeferredFileOutputStream(threshold, FileConstants.TEMP_FILE_PREFIX,
            null, null);

    RewindableInputStream content = null;

    try {
        /*
         * Wrap the output in a buffered stream and protect against 'zip bombs'.
         */
        SizeLimitedOutputStream buffered = new SizeLimitedOutputStream(new BufferedOutputStream(output),
                maxSize);

        Writer writer = new OutputStreamWriter(buffered, TextExtractor.ENCODING);

        try {
            writerHandler.write(writer);
        } finally {
            /*
             * Must close to make sure all data is written. 
             * 
             * Note: if DeferredFileOutputStream uses a file, the file should NOT 
             * be deleted here because it will be deleted when the returned 
             * DeferredBufferedInputStream is closed.
             */
            writer.close();
        }

        content = new RewindableInputStream(MiscIOUtils.toInputStream(output), threshold);

        handler.textEvent(new ExtractedPartImpl(context, content, buffered.getByteCount()));
    } catch (IOException e) {
        /*
         * Must close the RewindableInputStream to prevent a possible temp file leak
         */
        IOUtils.closeQuietly(content);

        /*
         * Delete the tempfile (if) used by DeferredFileOutputStream.
         */
        IOUtils.closeQuietly(output);
        FileUtils.deleteQuietly(output.getFile());

        throw e;
    } catch (RuntimeException e) {
        /*
         * Must close the RewindableInputStream to prevent a possible temp file leak
         */
        IOUtils.closeQuietly(content);

        /*
         * Delete the tempfile (if) used by DeferredFileOutputStream.
         */
        IOUtils.closeQuietly(output);
        FileUtils.deleteQuietly(output.getFile());

        throw e;
    }
}

From source file:FileCopyUtils.java

/**
 * Copy the contents of the given Reader to the given Writer.
 * Closes both when done.//from  w ww  .  j  a va2  s  .  co m
 * @param in the Reader to copy from
 * @param out the Writer to copy to
 * @return the number of characters copied
 * @throws IOException in case of I/O errors
 */
public static int copy(Reader in, Writer out) throws IOException {

    try {
        int byteCount = 0;
        char[] buffer = new char[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            System.out.println("Could not close Reader" + ex);
        }
        try {
            out.close();
        } catch (IOException ex) {
            System.out.println("Could not close Writer:" + ex);
        }
    }
}