Example usage for java.io Reader close

List of usage examples for java.io Reader close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:Main.java

/**
 * Parses the given input stream and returns the corresponding desirialized
 * XML document.//from  www . ja  v  a  2  s  . c  o m
 * 
 * @param reader the reader containing the serialized XML document
 * @param isNamespaceAware
 * @return the deserialized DOM document
 * @throws Exception
 */
public static Document readXML(Reader reader, boolean isNamespaceAware) throws Exception {
    try {
        DocumentBuilder builder = getDocumentBuilder(isNamespaceAware);
        InputSource source = new InputSource(reader);
        Document doc = builder.parse(source);
        return doc;
    } finally {
        reader.close();
    }
}

From source file:com.weibo.api.motan.protocol.grpc.GrpcUtil.java

public static <T extends Message> MethodDescriptor.Marshaller<T> jsonMarshaller(final T defaultInstance) {
    final JsonFormat.Printer printer = JsonFormat.printer().preservingProtoFieldNames();
    final JsonFormat.Parser parser = JsonFormat.parser();
    final Charset charset = Charset.forName("UTF-8");

    return new MethodDescriptor.Marshaller<T>() {
        @Override//w w w  . j a v  a  2 s. c  om
        public InputStream stream(T value) {
            try {
                return new ByteArrayInputStream(printer.print(value).getBytes(charset));
            } catch (InvalidProtocolBufferException e) {
                throw Status.INTERNAL.withCause(e).withDescription("Unable to print json proto")
                        .asRuntimeException();
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public T parse(InputStream stream) {
            Message.Builder builder = defaultInstance.newBuilderForType();
            Reader reader = new InputStreamReader(stream, charset);
            T proto;
            try {
                parser.merge(reader, builder);
                proto = (T) builder.build();
                reader.close();
            } catch (InvalidProtocolBufferException e) {
                throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e)
                        .asRuntimeException();
            } catch (IOException e) {
                // Same for now, might be unavailable
                throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e)
                        .asRuntimeException();
            }
            return proto;
        }
    };
}

From source file:Main.java

public static String gzipToString(final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }//from  w  ww .j  av  a 2 s . c o  m
    InputStream instream = entity.getContent();
    if (instream == null) {
        return "";
    }
    // gzip logic start
    if (entity.getContentEncoding().getValue().contains("gzip")) {
        instream = new GZIPInputStream(instream);
    }
    // gzip logic end
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int i = (int) entity.getContentLength();
    if (i < 0) {
        i = 4096;
    }
    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }
    Reader reader = new InputStreamReader(instream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(i);
    try {
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

From source file:circleplus.app.http.AbstractHttpApi.java

private static String readStream(InputStream is, int len) throws UnsupportedEncodingException, IOException {
    Reader reader = new InputStreamReader(is, "UTF-8");
    try {/*from  w  w w  .  ja  va2 s . co m*/
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    } finally {
        reader.close();
    }
}

From source file:net.myrrix.common.io.IOUtils.java

/**
 * @param url URL whose contents are to be read
 * @return the contents of the URL, interpreted as a UTF-8 encoded string
 * @throws IOException if the URL can't be read or the file can't be written
 *///from w w w.  j  a  v a 2  s  .com
public static String readSmallTextFromURL(URL url) throws IOException {
    Reader in = new InputStreamReader(url.openStream(), Charsets.UTF_8);
    try {
        return CharStreams.toString(in);
    } finally {
        in.close();
    }
}

From source file:Main.java

/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
    try {//w  ww.  j a va 2s  .c  o  m
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        int count;
        while ((count = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, count);
        }
        return writer.toString();
    } finally {
        reader.close();
    }
}

From source file:net.eusashead.hateoas.hal.http.converter.HalTestUtils.java

/**
 * Read a Hal {@link ReadableRepresentation}
 * from the supplied file/*w w w  . j  a va2  s .c  om*/
 * @param path
 * @return
 */
public static ReadableRepresentation halFromFile(String path) {
    Reader reader = null;
    try {
        reader = new FileReader(new File(path));
        return representationFactory.readRepresentation(reader);
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(e);
    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            log.error(e);
        }
    }
}

From source file:nl.igorski.lib.utils.network.ResponseParser.java

private static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {
    if (entity == null)
        throw new IllegalArgumentException("HTTP entity may not be null");

    InputStream instream = entity.getContent();

    if (instream == null)
        return "";

    if (entity.getContentLength() > Integer.MAX_VALUE)
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");

    String charset = getContentCharSet(entity);

    if (charset == null)
        charset = HTTP.DEFAULT_CONTENT_CHARSET;

    Reader reader = new InputStreamReader(instream, charset);
    StringBuilder buffer = new StringBuilder();

    try {/*from   w w w  .jav  a  2 s.co  m*/
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

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

/**
 * Hier exportieren wir die Musterdatei mit dem uebergebenen
 * {@link AbstractFormatter}. Im Gegensatz zu
 * {@link #exportMusterdatei(AbstractFormatter, String)} verwenden wir
 * hier den {@link DatenpaketStreamer} und das {@link ImportListener}
 * interface, um den Export durchzufuehren.
 *
 * @param formatter the formatter//from w  w  w. j ava 2 s .co  m
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected static void exportMusterdatei(final AbstractFormatter formatter) throws IOException {
    Reader reader = new InputStreamReader(new FileInputStream(MUSTERDATEI), "ISO-8859-1");
    DatenpaketStreamer datenpaketStreamer = new DatenpaketStreamer(reader);
    datenpaketStreamer.register(formatter);
    try {
        datenpaketStreamer.readDatenpaket();
    } finally {
        reader.close();
    }
}

From source file:no.digipost.android.utilities.JSONUtilities.java

public static String getJsonStringFromInputStream(final InputStream inputStream) {
    String content = "";

    if (inputStream != null) {
        Writer writer = new StringWriter();
        int buffer_size = 1024;
        char[] buffer = new char[buffer_size];

        try {//w w w  .  ja  v  a 2 s.  com
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, ApiConstants.ENCODING),
                    buffer_size);
            int n;

            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }

            inputStream.close();
            reader.close();
            writer.close();
        } catch (Exception e) {
        }
        content = writer.toString();
    }
    return content;
}