Example usage for java.io Reader read

List of usage examples for java.io Reader read

Introduction

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

Prototype

public abstract int read(char cbuf[], int off, int len) throws IOException;

Source Link

Document

Reads characters into a portion of an array.

Usage

From source file:com.github.jknack.handlebars.TemplateLoader.java

/**
 * Load the template as string from a template repository.
 *
 * @param uri The resource's uri. Required.
 * @return The requested resource.//from   w  w  w.  j a v  a2  s .  c  om
 * @throws IOException If the resource cannot be loaded.
 */
public String loadAsString(final URI uri) throws IOException {
    Reader reader = new BufferedReader(load(uri));
    final int bufferSize = 1024;
    try {
        char[] cbuf = new char[bufferSize];
        StringBuilder sb = new StringBuilder(bufferSize);
        int len;
        while ((len = reader.read(cbuf, 0, bufferSize)) != -1) {
            sb.append(cbuf, 0, len);
        }
        return sb.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:SniffedXmlInputStream.java

private String sniffForXmlDecl(String encoding) throws IOException {
    mark(MAX_SNIFFED_BYTES);/*w w  w  .jav  a 2 s .  c om*/
    try {
        byte[] bytebuf = new byte[MAX_SNIFFED_BYTES];
        int bytelimit = readAsMuchAsPossible(bytebuf, 0, MAX_SNIFFED_BYTES);

        // BUGBUG in JDK: Charset.forName is not threadsafe.
        Charset charset = Charset.forName(encoding);
        Reader reader = new InputStreamReader(new ByteArrayInputStream(bytebuf, 0, bytelimit), charset);
        char[] buf = new char[bytelimit];
        int limit = 0;
        while (limit < bytelimit) {
            int count = reader.read(buf, limit, bytelimit - limit);
            if (count < 0)
                break;
            limit += count;
        }

        return extractXmlDeclEncoding(buf, 0, limit);
    } finally {
        reset();
    }
}

From source file:com.zimbra.common.util.ByteUtil.java

/**
 * Reads a <tt>String</tt> from the given <tt>Reader</tt>.  Reads
 * until the either end of the stream is hit or until <tt>length</tt> characters
 * are read./*from  ww w  .  j  a  v a2 s .c  o m*/
 *
 * @param reader the content source
 * @param length number of characters to read, or <tt>-1</tt> for no limit
 * @param close <tt>true</tt> to close the <tt>Reader</tt> when done
 * @return the content or an empty <tt>String</tt> if no content is available
 */
public static String getContent(Reader reader, int length, boolean close) throws IOException {
    if (reader == null || length == 0)
        return "";

    if (length < 0)
        length = Integer.MAX_VALUE;
    char[] buf = new char[Math.min(1024, length)];
    int totalRead = 0;
    StringBuilder retVal = new StringBuilder(buf.length);

    try {
        while (true) {
            int numToRead = Math.min(buf.length, length - totalRead);
            if (numToRead <= 0)
                break;
            int numRead = reader.read(buf, 0, numToRead);
            if (numRead < 0)
                break;
            retVal.append(buf, 0, numRead);
            totalRead += numRead;
        }
        return retVal.toString();
    } finally {
        if (close) {
            try {
                reader.close();
            } catch (IOException e) {
                ZimbraLog.misc.warn("Unable to close Reader", e);
            }
        }
    }
}

From source file:com.google.android.apps.body.LayersLoader.java

/** Synchronously loads a single layer. */
private Render.DrawGroup[] load(Context context, int layerResource) {
    // TODO(thakis): this method is kinda ugly.
    // TODO(thakis): if we can bundle the resource files, rewrite them so that no conversion
    //               needs to happen at load time. The utf8 stuff is clever, but mostly overhead
    //               for local files.

    // Timers for different loading phases.
    float jsonReadS = 0;
    float jsonParseS = 0;
    float textureS = 0;
    float fileReadS = 0;
    float fileDecodeS = 0;
    float colorBufferS = 0;

    Render.DrawGroup[] drawGroups = null;

    long jsonReadStartNS = System.nanoTime();
    JSONObject object = loadJsonResource(context, layerResource);
    jsonReadS = (System.nanoTime() - jsonReadStartNS) / 1e9f;

    long jsonParseStartNS = System.nanoTime();
    Map<Integer, List<Loader>> toBeLoaded = new HashMap<Integer, List<Loader>>();
    try {/* ww w.  j a  v  a  2 s. c  om*/
        JSONArray dataDrawGroups = object.getJSONArray("draw_groups");
        drawGroups = new Render.DrawGroup[dataDrawGroups.length()];
        for (int i = 0; i < drawGroups.length; ++i) {
            if (mCancelled)
                return null;

            JSONObject drawGroup = dataDrawGroups.getJSONObject(i);
            drawGroups[i] = new Render.DrawGroup();
            if (drawGroup.has("texture"))
                drawGroups[i].texture = drawGroup.getString("texture");
            else if (drawGroup.has("diffuse_color")) {
                JSONArray color = drawGroup.getJSONArray("diffuse_color");
                drawGroups[i].diffuseColor = new float[3];
                for (int j = 0; j < 3; ++j)
                    drawGroups[i].diffuseColor[j] = (float) color.getDouble(j);
            }
            JSONArray draws = drawGroup.getJSONArray("draws");
            drawGroups[i].draws = new ArrayList<Render.Draw>(draws.length());
            for (int j = 0; j < draws.length(); ++j) {
                JSONObject jsonDraw = draws.getJSONObject(j);
                Render.Draw draw = new Render.Draw();
                draw.geometry = jsonDraw.getString("geometry");
                draw.offset = jsonDraw.getJSONArray("range").getInt(0);
                draw.count = jsonDraw.getJSONArray("range").getInt(1);
                drawGroups[i].draws.add(draw);
            }
            long textureReadStartNS = System.nanoTime();
            loadTexture(mContext, drawGroups[i]);
            textureS += (System.nanoTime() - textureReadStartNS) / 1e9f;

            String indices = drawGroup.getString("indices");
            FP.FPEntry indicesFP = FP.get(indices);
            if (toBeLoaded.get(indicesFP.file) == null)
                toBeLoaded.put(indicesFP.file, new ArrayList<Loader>());
            toBeLoaded.get(indicesFP.file).add(new IndexLoader(drawGroups[i], indicesFP));

            String attribs = drawGroup.getString("attribs");
            FP.FPEntry attribsFP = FP.get(attribs);
            if (toBeLoaded.get(attribsFP.file) == null)
                toBeLoaded.put(attribsFP.file, new ArrayList<Loader>());
            toBeLoaded.get(attribsFP.file).add(new AttribLoader(drawGroups[i], attribsFP));

            drawGroups[i].numIndices = drawGroup.getInt("numIndices");
        }
    } catch (JSONException e) {
        Log.e("Body", e.toString());
    }
    jsonParseS = (System.nanoTime() - jsonParseStartNS) / 1e9f - textureS;

    for (int resource : toBeLoaded.keySet()) {
        if (mCancelled)
            return null;

        long fileReadStartNS = System.nanoTime();
        char[] data = new char[0];
        InputStream is = mContext.getResources().openRawResource(resource);
        try {
            // Comment from the ApiDemo content/ReadAsset.java in the Android SDK:
            // "We guarantee that the available method returns the total
            //  size of the asset...  of course, this does mean that a single
            //  asset can't be more than 2 gigs."
            data = new char[is.available()];
            Reader in = new InputStreamReader(is, "UTF-8");
            in.read(data, 0, data.length);
        } catch (UnsupportedEncodingException e) {
            Log.e("Body", e.toString());
        } catch (IOException e) {
            Log.e("Body", e.toString());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.e("Body", e.toString());
            }
        }
        fileReadS += (System.nanoTime() - fileReadStartNS) / 1.0e9f;
        long fileDecodeStartNS = System.nanoTime();
        for (Loader l : toBeLoaded.get(resource)) {
            if (mCancelled)
                return null;

            l.load(data);
        }
        fileDecodeS += (System.nanoTime() - fileDecodeStartNS) / 1.0e9f;
    }

    long colorBufferStartNS = System.nanoTime();
    for (Render.DrawGroup drawGroup : drawGroups) {
        if (mCancelled)
            return null;
        createColorBuffer(drawGroup);
    }
    colorBufferS = (System.nanoTime() - colorBufferStartNS) / 1e9f;

    Log.i("Body", "JSON read: " + jsonReadS + ", JSON parse: " + jsonParseS + ", texture: " + textureS
            + ", res read: " + fileReadS + ", res decode: " + fileDecodeS + ", colorbuf: " + colorBufferS);

    return drawGroups;
}

From source file:net.sf.vfsjfilechooser.accessories.bookmarks.BookmarksReader.java

public BookmarksReader(File bookmarksFile) {
    entries = new ArrayList<TitledURLEntry>();
    Reader reader = null;
    try {// w  w w . java2 s .c  o m
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(new BookmarksHandler());

        reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookmarksFile), "UTF-8"));

        // read 1st 2 bytes to support multiple encryptions
        char[] code = new char[2];
        reader.read(code, 0, 2);
        LOGGER.debug("code=" + String.valueOf(code) + "=");
        if ((code[0] == 'b') && (code[1] == '1')) {
            LOGGER.debug("in encrypted code section");
            // read the encrypted file
            InputStream is = new FileInputStream(bookmarksFile);

            int the_length = (int) bookmarksFile.length() - 2;
            LOGGER.debug("raw_length=" + (the_length + 2));
            if (the_length <= 0)
                the_length = 1;
            LOGGER.debug("fixed_length=" + the_length);
            byte[] code2 = new byte[2];
            byte[] outhex = new byte[the_length];
            try {
                is.read(code2);
                is.read(outhex);
                // is.read(outhex,2,the_length);
                is.close();
            } catch (Exception e) {
                LOGGER.info("exception reading encrypted file" + e);
            } finally {
                IOUtils.closeQuietly(is);
            }

            byte[] out = Util.hexByteArrayToByteArray(outhex);

            // do the decryption

            byte[] raw = new byte[16];
            raw[0] = (byte) 1;
            raw[2] = (byte) 23;
            raw[3] = (byte) 24;
            raw[4] = (byte) 2;
            raw[5] = (byte) 99;
            raw[6] = (byte) 200;
            raw[7] = (byte) 202;
            raw[8] = (byte) 209;
            raw[9] = (byte) 199;
            raw[10] = (byte) 181;
            raw[11] = (byte) 255;
            raw[12] = (byte) 33;
            raw[13] = (byte) 210;
            raw[14] = (byte) 214;
            raw[15] = (byte) 216;

            SecretKeySpec skeyspec = new SecretKeySpec(raw, "Blowfish");
            Cipher cipher = Cipher.getInstance("Blowfish");
            cipher.init(Cipher.DECRYPT_MODE, skeyspec);
            byte[] decrypted = cipher.doFinal(out);

            // convert decrypted into a bytestream and parse it
            ByteArrayInputStream bstream = new ByteArrayInputStream(decrypted);

            InputSource inputSource = new InputSource(bstream);
            xmlReader.parse(inputSource);
            LOGGER.debug("leaving encrypted code section");
        } else {
            LOGGER.debug("in decrypted code section");
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookmarksFile), "UTF-8"));
            InputSource inputSource = new InputSource(reader);
            xmlReader.parse(inputSource);
            LOGGER.debug("leaving decrypted code section");
        }
    } catch (SAXParseException e) {
        StringBuilder sb = new StringBuilder();
        sb.append("Error parsing xml bookmarks file").append("\n").append(e.getLineNumber()).append(":")
                .append(e.getColumnNumber()).append("\n").append(e.getMessage());
        throw new RuntimeException(sb.toString(), e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Bookmarks file doesn't exist!", e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                LOGGER.error("Unable to close bookmarks stream", ioe);
            }
        }
    }
}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testSendBinary() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    server.start(new Supplier<TelnetHandler>() {
        @Override//from  w w w.  ja v  a 2s.com
        public TelnetHandler get() {
            return new TelnetHandler() {
                private TelnetConnection conn;

                @Override
                protected void onOpen(TelnetConnection conn) {
                    this.conn = conn;
                    conn.writeWillOption(Option.BINARY);
                }

                @Override
                protected void onSendBinary(boolean binary) {
                    if (binary) {
                        conn.write(new byte[] { 'h', 'e', 'l', 'l', 'o', -1 });
                        latch.countDown();
                    } else {
                        fail("Was not expecting a don't for binary option");
                    }
                }

                @Override
                protected void onReceiveBinary(boolean binary) {
                    if (binary) {
                        fail("Was not expecting a will for binary option");
                    }
                }
            };
        }
    });
    client.setOptionHandler(new SimpleOptionHandler(0, false, false, false, true));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    client.client.registerSpyStream(baos);
    client.connect("localhost", 4000);
    latch.await();
    Reader reader = new InputStreamReader(client.client.getInputStream());
    int expectedLen = 5;
    char[] hello = new char[expectedLen];
    int num = 0;
    while (num < expectedLen) {
        int read = reader.read(hello, num, expectedLen - num);
        if (read == -1) {
            fail("Unexpected");
        }
        num += read;
    }
    assertEquals(5, num);
    assertEquals("hello", new String(hello));
    long now = System.currentTimeMillis();
    byte[] data;
    while ((data = baos.toByteArray()).length < 10) {
        assertTrue(System.currentTimeMillis() - now < 10000);
        Thread.sleep(5);
    }
    assertEquals((byte) 'h', data[3]);
    assertEquals((byte) 'e', data[4]);
    assertEquals((byte) 'l', data[5]);
    assertEquals((byte) 'l', data[6]);
    assertEquals((byte) 'o', data[7]);
    assertEquals((byte) -1, data[8]);
    assertEquals((byte) -1, data[9]);
}

From source file:com.zimbra.cs.mime.Mime.java

/** Reads the specified <code>InputStream</code> into a <code>String</code>.
 *  <code>contentType</code> must of type "text/*". If a valid charset
 *  parameter is present in the Content-Type string, it is used as the
 *  charset for decoding the text.  If not, we fall back to the user's
 *  default charset preference.  If both of those options fail, the
 *  platform default is used./*from w w w .  j  a  v a2s.c om*/
 *
 * @param input  The InputStream to decode.
 * @param contentType  The Content-Type of the stream, which must be "text/*".
 * @parame defaultCharset  The user's default charset preference */
public static String decodeText(InputStream input, String contentType, String defaultCharset)
        throws IOException {
    StringBuilder buffer = new StringBuilder();
    try {
        Reader reader = getTextReader(input, contentType, defaultCharset);
        char[] cbuff = new char[MAX_DECODE_BUFFER];
        int num;
        while ((num = reader.read(cbuff, 0, cbuff.length)) != -1)
            buffer.append(cbuff, 0, num);
    } finally {
        ByteUtil.closeStream(input);
    }
    return buffer.toString();
}

From source file:ConcatReader.java

/**
 * Read characters into a portion of an array. This method will block until
 * some input is available, an I/O error occurs, or the end of all underlying
 * streams are reached.// w ww  . java 2s. c  o m
 * <p>
 * If this class in not done accepting readers and the end of the last known
 * stream is reached, this method will block forever unless another thread
 * adds a reader or interrupts.
 *
 * @param cbuf Destination buffer
 * @param off Offset at which to start storing characters
 * @param len Maximum number of characters to read
 * @return The number of characters read, or -1 if the end of the stream has been reached
 *
 * @throws IOException - If an I/O error occurs
 * @throws NullPointerException - If the buffer is null.
 * @throws IndexOutOfBoundsException - if length or offset are not possible.
 *
 * @since ostermillerutils 1.04.00
 */
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
    if (off < 0 || len < 0 || off + len > cbuf.length)
        throw new IndexOutOfBoundsException();
    if (closed)
        throw new IOException("Reader closed");
    int r = -1;
    while (r == -1) {
        Reader in = getCurrentReader();
        if (in == null) {
            if (doneAddingReaders)
                return -1;
            try {
                Thread.sleep(100);
            } catch (InterruptedException iox) {
                throw new IOException("Interrupted");
            }
        } else {
            r = in.read(cbuf, off, len);
            if (r == -1)
                advanceToNextReader();
        }
    }
    return r;
}

From source file:org.epop.dataprovider.googlescholar.GoogleScholarProvider.java

@Override
protected List<Literature> parsePage(Reader page) throws DatalayerException {
    List<Literature> papers = new ArrayList<Literature>();
    Document doc = null;/* ww  w  .  j a  va 2  s .  c om*/
    try {
        StringBuilder builder = new StringBuilder();
        int charsRead = -1;
        char[] chars = new char[100];
        do {
            charsRead = page.read(chars, 0, chars.length);
            // if we have valid chars, append them to end of string.
            if (charsRead > 0)
                builder.append(chars, 0, charsRead);
        } while (charsRead > 0);
        doc = Jsoup.parse(builder.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } // for (Document doc : docs) {

    for (Element article : doc.select(".gs_r")) {
        try {

            LiteratureBuilder litBuilder = new LiteratureBuilder();

            // type
            String typeString = article.select(".gs_ct2").text();
            if (typeString == null)
                typeString = "";
            if (typeString.equals("[C]"))
                continue; // skip citations
            litBuilder.setType(getLiteratureType(typeString));

            // title
            String title = article.select(".gs_rt a").text();
            title = title.replaceAll("\u0097", "-");
            title = title.replaceAll("", "...");
            if (title.isEmpty())
                throw new DatalayerException("title retrieved by parsing is empty");
            litBuilder.setTitle(title);

            // website URL
            if (litBuilder.getWebsiteURLs() == null)
                litBuilder.setWebsiteURLs(new HashSet<Link>());
            try {
                String linkURL = article.select(".gs_rt a").attr("href");
                litBuilder.getWebsiteURLs().add(new Link(linkURL));
            } catch (URISyntaxException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            try {
                // cluster link
                String googleLinkURL = "http://scholar.google.com"
                        + article.select(".gs_fl .gs_nph").attr("href");
                litBuilder.getWebsiteURLs().add(new Link("Google Scholar", googleLinkURL));
                // scholar ID
                Matcher idMatcher = ID_PATTERN.matcher(googleLinkURL);
                if (idMatcher.find())
                    litBuilder.setgScholarID(idMatcher.group(1));
                // else
                // TODO error handling
            } catch (URISyntaxException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            String abstractText = article.select(".gs_rs").text();
            litBuilder.setAbstractText(abstractText);

            String rawHTML = article.select(".gs_a").html();
            if (rawHTML.isEmpty()) // no authors
                continue;

            // split by " - " (authors - publication, year - publisher)
            String[] splits = rawHTML.split(" - ");
            //            if (splits.length != 3)
            //               throw new DatalayerException(
            //                     "dashTokenizer should have three sections (authors - publication, year - publisher), found "
            //                           + splits.length
            //                           + "; maybe Google Scholar layout has changed");
            String namesHTML = "", publicationHTML = "", publisherHTML = "";
            if (splits.length > 0) {
                namesHTML = splits[0];
                namesHTML = namesHTML.replace(", ", "");
            }
            if (splits.length == 2) {
                publisherHTML = splits[1];
            }
            if (splits.length > 3) {
                publicationHTML = splits[1];
                publisherHTML = splits[2];
            }

            // authors
            try {
                List<Author> authors = getAuthorsFromHTMLSection(namesHTML);
                litBuilder.setAuthors(new HashSet<>(authors));
            } catch (PatternMismatchException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            // publication
            String[] commaSplit = publicationHTML.split(", ");
            if (commaSplit.length == 2) {
                String publication = commaSplit[0];
                publication = publication.replaceAll("\u0097", "-");
                publication = publication.replaceAll("", "...");
                litBuilder.setPublicationContext(publication);
                try {
                    Integer year = Integer.parseInt(commaSplit[1]);
                    litBuilder.setYear(year);
                } catch (NumberFormatException e) {
                    // throw new ServiceException(
                    // "publicationHTML subsection has invalid format: failed to parse publication year");
                    // TODO (low) logging

                }
            } else {
                // TODO logging/notify user
            }

            // publisher
            litBuilder.setPublisher(publisherHTML);

            // citations
            String citedby = article.select(".gs_fl a[href*=cites]").text();
            Matcher cm = CITES_PATTERN.matcher(citedby);
            try {
                int cites = cm.find() ? Integer.parseInt(cm.group(1)) : 0;
                litBuilder.setgScholarNumCitations(cites);
            } catch (NumberFormatException e) {
                // TODO
            }

            // fulltext
            String fulltextURL = article.select("div.gs_md_wp.gs_ttss a").attr("href");
            Set<Link> fullLinks = new HashSet<>();
            try {
                fullLinks.add(new Link(fulltextURL));
                litBuilder.setFulltextURLs(fullLinks);
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            papers.add(litBuilder.getObject());

        } catch (Exception e) {
            malformed.add(e.getMessage());
        }
    }
    // }

    // if (headerContent.startsWith("User profiles")) {
    // // only the first part
    // Element hrefPart = seg.getAllElements().get(0);
    // String link = hrefPart.getAttributeValue("href");
    // assert link.startsWith("/citations");
    // String[] data = link.split("[?|&|=]");
    // System.out.println("id found for user " + data[2]);
    // return GoogleScholarGetterFromId.getFromId(data[2]);
    //
    // docs.clear();
    System.err.println(malformed + " " + malformed.size());

    return papers;
}

From source file:edu.lternet.pasta.portal.Harvester.java

/**
 *  Reads character data from the <code>Reader</code> provided, using a 
 *  buffered read. Returns data as a <code>StringBufer</code>
 *
 *  @param  reader              <code>Reader</code> object to be read
 *
 *  @param  closeWhenFinished   <code>boolean</code> value to indicate 
 *                              whether Reader should be closed when reading
 *                              finished
 *
 *  @return                     <code>StringBuffer</code> containing  
 *                              characters read from the <code>Reader</code>
 *
 *  @throws IOException if there are problems accessing or using the Reader.
 *///from  w w  w.  j  av a 2 s  .c o m
public StringBuffer getAsStringBuffer(Reader reader, boolean closeWhenFinished) throws IOException {
    if (reader == null)
        return null;

    StringBuffer sb = new StringBuffer();

    try {
        char[] buff = new char[4096];
        int numCharsRead;

        while ((numCharsRead = reader.read(buff, 0, buff.length)) != -1) {
            sb.append(buff, 0, numCharsRead);
        }
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (closeWhenFinished) {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException ce) {
                ce.printStackTrace();
            }
        }
    }

    return sb;
}