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:Main.java

public static int read(Reader input, char[] buffer, int offset, int length) throws IOException {
    if (length < 0) {
        throw new IllegalArgumentException("Length must not be negative: " + length);
    } else {/*from w  ww.  j  av a2 s.  c  o  m*/
        int remaining;
        int count;
        for (remaining = length; remaining > 0; remaining -= count) {
            int location = length - remaining;
            count = input.read(buffer, offset + location, remaining);
            if (-1 == count) {
                break;
            }
        }

        return length - remaining;
    }
}

From source file:Main.java

/**
 * Read characters from an input character stream.
 * This implementation guarantees that it will read as many characters
 * as possible before giving up; this may not always be the case for
 * subclasses of {@link Reader}.//from www .j av a  2 s .com
 *
 * @param input  where to read input from
 * @param buffer destination
 * @param offset inital offset into buffer
 * @param length length to read, must be >= 0
 * @return actual length read; may be less than requested if EOF was reached
 * @throws IOException if a read error occurs
 * @since 2.2
 */
public static int read(Reader input, char[] buffer, int offset, int length) throws IOException {
    if (length < 0) {
        throw new IllegalArgumentException("Length must not be negative: " + length);
    }
    int remaining = length;
    while (remaining > 0) {
        int location = length - remaining;
        int count = input.read(buffer, offset + location, remaining);
        if (EOF == count) { // EOF
            break;
        }
        remaining -= count;
    }
    return length - remaining;
}

From source file:com.galactogolf.genericobjectmodel.levelloader.LevelSet.java

public static ArrayList<LevelSet> loadAllLevelSetsFromInternalStorage(Context context)
        throws LevelLoadingException {

    File levelsDir = context.getDir(GameConstants.LOCATION_OF_LEVELS_CREATED_BY_USER, Context.MODE_PRIVATE);
    File[] levelSetFiles = levelsDir.listFiles();
    ArrayList<LevelSet> levelSets = new ArrayList<LevelSet>();
    for (int i = 0; i < levelSetFiles.length; i++) {
        InputStream input;/*from w  w w . j  ava 2  s  .  co  m*/
        try {
            input = new FileInputStream(levelSetFiles[i]);
        } catch (FileNotFoundException e) {
            Log.e("File loading error", e.getMessage());
            throw new LevelLoadingException(e.getMessage());
        }
        StringBuilder sb = new StringBuilder();
        final char[] buffer = new char[500];
        Reader in = new InputStreamReader(input);
        int read;
        try {
            do {
                read = in.read(buffer, 0, buffer.length);
                if (read > 0) {
                    sb.append(buffer, 0, read);
                }
            } while (read >= 0);
        } catch (IOException e) {
            Log.e("File loading error", e.getMessage());
            throw new LevelLoadingException(e.getMessage());
        }
        String data = sb.toString();
        try {
            levelSets.add(JSONSerializer.fromLevelSetJSON(new JSONObject(data)));
        } catch (JSONException e) {
            Log.e("File loading error", e.getMessage());
            throw new LevelLoadingException(e.getMessage());
        }

    }
    return levelSets;

}

From source file:Main.java

public static long skip(Reader input, long toSkip) throws IOException {
    if (toSkip < 0L) {
        throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
    } else {/*from   w  w  w .  j av  a  2  s .  co m*/
        if (SKIP_CHAR_BUFFER == null) {
            SKIP_CHAR_BUFFER = new char[2048];
        }

        long remain;
        long n;
        for (remain = toSkip; remain > 0L; remain -= n) {
            n = (long) input.read(SKIP_CHAR_BUFFER, 0, (int) Math.min(remain, 2048L));
            if (n < 0L) {
                break;
            }
        }

        return toSkip - remain;
    }
}

From source file:Main.java

/**
 * Read characters from an input character stream.
 * This implementation guarantees that it will read as many characters
 * as possible before giving up; this may not always be the case for
 * subclasses of {@link Reader}.//from ww w  .jav  a 2  s  . c o m
 * 
 * @param input where to read input from
 * @param buffer destination
 * @param offset inital offset into buffer
 * @param length length to read, must be >= 0
 * @return actual length read; may be less than requested if EOF was reached
 * @throws IOException if a read error occurs
 */
public static int read(Reader input, char[] buffer, int offset, int length) throws IOException {
    if (length < 0) {
        throw new IllegalArgumentException("Length must not be negative: " + length);
    }
    int remaining = length;
    while (remaining > 0) {
        int location = (length - remaining);
        int count = input.read(buffer, location, remaining);
        if (-1 == count) { // EOF
            break;
        }
        remaining -= count;
    }
    return length - remaining;
}

From source file:net.lightbody.bmp.proxy.jetty.util.IO.java

/** Copy Reader to Writer for byteCount bytes or until EOF or exception.
 *///www . jav  a  2s  .  com
public static void copy(Reader in, Writer out, long byteCount) throws IOException {
    char buffer[] = new char[bufferSize];
    int len = bufferSize;

    if (byteCount >= 0) {
        while (byteCount > 0) {
            if (byteCount < bufferSize)
                len = in.read(buffer, 0, (int) byteCount);
            else
                len = in.read(buffer, 0, bufferSize);

            if (len == -1)
                break;

            byteCount -= len;
            out.write(buffer, 0, len);
        }
    } else {
        while (true) {
            len = in.read(buffer, 0, bufferSize);
            if (len == -1)
                break;
            out.write(buffer, 0, len);
        }
    }
}

From source file:org.zenoss.zep.dao.impl.DaoUtils.java

private static String convertStreamToStr(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {/* w  w w .j ava  2  s .co m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer, 0, 1024)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.aoindustries.website.signup.ServerConfirmationCompletedActionHelper.java

/**
 * Sends a summary email and returns <code>true</code> if successful.
 *///from ww w .  j a v  a2s . c  o m
private static boolean sendSummaryEmail(ActionServlet servlet, HttpServletRequest request, String pkey,
        String statusKey, String recipient, SiteSettings siteSettings, PackageDefinition packageDefinition,
        SignupCustomizeServerForm signupCustomizeServerForm,
        SignupCustomizeManagementForm signupCustomizeManagementForm, SignupBusinessForm signupBusinessForm,
        SignupTechnicalForm signupTechnicalForm, SignupBillingInformationForm signupBillingInformationForm) {
    try {
        Locale userLocale = ThreadLocale.get();
        // Find the locale and related resource bundles
        String charset = Skin.getCharacterSet(userLocale);

        // Generate the email contents
        CharArrayWriter cout = new CharArrayWriter();
        ChainWriter emailOut = new ChainWriter(cout);
        String htmlLang = getHtmlLang(userLocale);
        emailOut.print(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
                        + "<html xmlns=\"http://www.w3.org/1999/xhtml\"");
        if (htmlLang != null)
            emailOut.print(" lang=\"").print(htmlLang).print("\" xml:lang=\"").print(htmlLang).print('"');
        emailOut.print(">\n" + "<head>\n" + "    <meta http-equiv='Content-Type' content='text/html; charset=")
                .print(charset).print("' />\n");
        // Embed the text-only style sheet
        InputStream cssIn = servlet.getServletContext().getResourceAsStream("/textskin/global.css");
        if (cssIn != null) {
            try {
                emailOut.print("    <style type=\"text/css\">\n" + "      /* <![CDATA[ */\n");
                Reader cssReader = new InputStreamReader(cssIn);
                try {
                    char[] buff = new char[4096];
                    int ret;
                    while ((ret = cssReader.read(buff, 0, 4096)) != -1)
                        emailOut.write(buff, 0, ret);
                } finally {
                    cssIn.close();
                }
                emailOut.print("      /* ]]> */\n" + "    </style>\n");
            } finally {
                cssIn.close();
            }
        } else {
            servlet.log("Warning: Unable to find resource: /global/textskin.css");
        }
        emailOut.print(
                "</head>\n" + "<body>\n" + "<table style='border:0px' cellpadding=\"0\" cellspacing=\"0\">\n"
                        + "    <tr><td style='white-space:nowrap' colspan=\"3\">\n" + "        ")
                .print(accessor.getMessage(statusKey, pkey)).print("<br />\n" + "        <br />\n" + "        ")
                .print(accessor.getMessage("serverConfirmationCompleted.belowIsSummary"))
                .print("<br />\n" + "        <hr />\n" + "    </td></tr>\n" + "    <tr><th colspan=\"3\">")
                .print(accessor.getMessage("steps.selectServer.label")).print("</th></tr>\n");
        SignupSelectServerActionHelper.printConfirmation(emailOut, packageDefinition);
        emailOut.print("    <tr><td colspan=\"3\">&#160;</td></tr>\n" + "    <tr><th colspan=\"3\">")
                .print(accessor.getMessage("steps.customizeServer.label")).print("</th></tr>\n");
        AOServConnector rootConn = siteSettings.getRootAOServConnector();
        SignupCustomizeServerActionHelper.printConfirmation(request, emailOut, rootConn, packageDefinition,
                signupCustomizeServerForm);
        if (signupCustomizeManagementForm != null) {
            emailOut.print("    <tr><td colspan=\"3\">&#160;</td></tr>\n" + "    <tr><th colspan=\"3\">")
                    .print(accessor.getMessage("steps.customizeManagement.label")).print("</th></tr>\n");
            SignupCustomizeManagementActionHelper.printConfirmation(request, emailOut, rootConn,
                    signupCustomizeManagementForm);
        }
        emailOut.print("    <tr><td colspan=\"3\">&#160;</td></tr>\n" + "    <tr><th colspan=\"3\">")
                .print(accessor.getMessage("steps.businessInfo.label")).print("</th></tr>\n");
        SignupBusinessActionHelper.printConfirmation(emailOut, rootConn, signupBusinessForm);
        emailOut.print("    <tr><td colspan=\"3\">&#160;</td></tr>\n" + "    <tr><th colspan=\"3\">")
                .print(accessor.getMessage("steps.technicalInfo.label")).print("</th></tr>\n");
        SignupTechnicalActionHelper.printConfirmation(emailOut, rootConn, signupTechnicalForm);
        emailOut.print("    <tr><td colspan=\"3\">&#160;</td></tr>\n" + "    <tr><th colspan=\"3\">")
                .print(accessor.getMessage("steps.billingInformation.label")).print("</th></tr>\n");
        SignupBillingInformationActionHelper.printConfirmation(emailOut, signupBillingInformationForm);
        emailOut.print("</table>\n" + "</body>\n" + "</html>\n");
        emailOut.flush();

        // Send the email
        Brand brand = siteSettings.getBrand();
        Mailer.sendEmail(
                HostAddress.valueOf(brand.getSignupEmailAddress().getDomain().getAOServer().getHostname()),
                "text/html", charset, brand.getSignupEmailAddress().toString(), brand.getSignupEmailDisplay(),
                Collections.singletonList(recipient),
                accessor.getMessage("serverConfirmationCompleted.email.subject", pkey), cout.toString());

        return true;
    } catch (RuntimeException err) {
        servlet.log("Unable to send sign up details to " + recipient, err);
        return false;
    } catch (IOException err) {
        servlet.log("Unable to send sign up details to " + recipient, err);
        return false;
    } catch (SQLException err) {
        servlet.log("Unable to send sign up details to " + recipient, err);
        return false;
    } catch (MessagingException err) {
        servlet.log("Unable to send sign up details to " + recipient, err);
        return false;
    }
}

From source file:Repackage.java

public static void copy(Reader r, Writer w) throws IOException {
    char[] buffer = new char[1024 * 16];

    for (;;) {/*from  ww w  .j  av a  2s .  c  o  m*/
        int n = r.read(buffer, 0, buffer.length);

        if (n < 0)
            break;

        w.write(buffer, 0, n);
    }
}

From source file:gov.nrel.bacnet.consumer.BACnet.java

public static String readFile(String file, Charset cs) throws IOException {
    // No real need to close the BufferedReader/InputStreamReader
    // as they're only wrapping the stream
    FileInputStream stream = new FileInputStream(file);
    try {// ww  w  . j a va2  s. c o  m
        Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[8192];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        return builder.toString();
    } finally {
        // Potential issue here: if this throws an IOException,
        // it will mask any others. Normally I'd use a utility
        // method which would log exceptions and swallow them
        stream.close();
    }
}