Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

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

Prototype

public 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:eu.anynet.java.util.HttpClient.java

/**
 * Read from inputstream and get the result as string
 * @param stream The stream/*from  www  .  ja  v  a2 s. c  o  m*/
 * @param maxlength Max bytes to fetch, set <1 to disable max length
 * @return The string
 * @throws IOException
 */
public static String toString(InputStream stream, int maxlength) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    Writer resultbuffer = new StringWriter();

    char buffer[] = new char[1024];
    int totalReadSize = 0, currentRead = 0, writelength = 0;

    while ((currentRead = reader.read(buffer, 0, buffer.length)) != -1) {
        totalReadSize += currentRead;
        writelength = currentRead;
        if (maxlength > 0 && totalReadSize > maxlength) {
            writelength = maxlength - totalReadSize;
        }

        if (writelength > 0) {
            resultbuffer.write(buffer, 0, writelength);
        } else {
            break;
        }
    }

    reader.close();
    return resultbuffer.toString();
}

From source file:autohit.common.Utils.java

/**
 *  Read a file into a String.//from ww w . j ava2  s .co m
 * @param f File to read
 * @return string if successful or otherwise null
 */
public static String loadFile2String(File f) {

    StringBuffer buffer = new StringBuffer();
    try {

        char[] buf = new char[1024];
        int sbuf;

        BufferedReader bis = new BufferedReader(new FileReader(f));

        sbuf = bis.read(buf, 0, 1024);
        while (sbuf > 0) {
            buffer.append(buf, 0, sbuf);
            sbuf = bis.read(buf, 0, 1024);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return buffer.toString();
}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

private static void checkResultForError(final String fileName) throws IOException, TPUException {

    final Path filePath = Paths.get(fileName);
    final char[] buffer = new char[MAX_BUFFER_LENGTH];
    BufferedReader bufferedReader = Files.newBufferedReader(filePath, Charsets.UTF_8);
    final int readCharacters = bufferedReader.read(buffer, 0, MAX_BUFFER_LENGTH);

    if (readCharacters <= -1) {

        LOG.debug("couldn't check file for errors; no file content in file '{}'", fileName);

        bufferedReader.close();/*w  ww.  j  a va 2 s.c o m*/

        return;
    }

    final String bufferString = String.valueOf(buffer);

    if (bufferString.startsWith(ERROR_MESSAGE_START)) {

        bufferedReader.close();

        throw new TPUException(bufferString);
    }
}

From source file:Main.java

/**
 * @param http/*from  w ww. ja va 2s  .c om*/
 * @return extracted title of page from html.
 * @throws IOException
 */
public static String getPageTitle(String linkUrl) throws IOException {
    URL url = new URL(linkUrl);
    URLConnection conn = null;
    try {

        conn = url.openConnection();

        String type = conn.getContentType();
        if (type != null && !type.toLowerCase().contains("text/html"))
            return null; // if not html, we can't get title. Return from here.
        else {
            // read response stream
            BufferedReader bufReader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            int n = 0;
            int readCount = 0;
            char[] buf = new char[1024];
            StringBuilder content = new StringBuilder();

            // read till end of file or 8 times the buffer (no need to read
            // all data, assuming we get content in first 8 reads)
            while (readCount < 8 && (n = bufReader.read(buf, 0, buf.length)) != -1) {
                content.append(buf, 0, n);
                readCount++;
            }
            bufReader.close();

            // extract the title
            Matcher matcher = HTML_TITLE_PATTERN.matcher(content);
            if (matcher.find()) {

                // replace whitespaces and HTML brackets

                return matcher.group(1).replaceAll("[\\s\\<>]+", " ").trim();
            } else
                return null;
        }
    } finally {
        //any cleanup?
    }
}

From source file:com.hazelcast.simulator.utils.FileUtils.java

public static String fileAsText(File file) {
    FileInputStream stream = null;
    InputStreamReader streamReader = null;
    BufferedReader reader = null;
    try {/*from   w  w  w .j ava  2s . c om*/
        stream = new FileInputStream(file);
        streamReader = new InputStreamReader(stream);
        reader = new BufferedReader(streamReader);

        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[READ_BUFFER_SIZE];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        return builder.toString();
    } catch (IOException e) {
        throw new FileUtilsException(e);
    } finally {
        closeQuietly(reader);
        closeQuietly(streamReader);
        closeQuietly(stream);
    }
}

From source file:com.andrewshu.android.reddit.common.Common.java

/**
 * Get a new modhash by scraping and return it
 * //from  w  w w.  j  ava 2  s .c o  m
 * @param client
 * @return
 */
public static String doUpdateModhash(HttpClient client) {
    final Pattern MODHASH_PATTERN = Pattern.compile("modhash: '(.*?)'");
    String modhash;
    HttpEntity entity = null;
    // The pattern to find modhash from HTML javascript area
    try {
        HttpGet httpget = new HttpGet(Constants.MODHASH_URL);
        HttpResponse response = client.execute(httpget);

        // For modhash, we don't care about the status, since the 404 page has the info we want.
        //          status = response.getStatusLine().toString();
        //           if (!status.contains("OK"))
        //              throw new HttpException(status);

        entity = response.getEntity();

        BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
        // modhash should appear within first 1200 chars
        char[] buffer = new char[1200];
        in.read(buffer, 0, 1200);
        in.close();
        String line = String.valueOf(buffer);
        entity.consumeContent();

        if (StringUtils.isEmpty(line)) {
            throw new HttpException("No content returned from doUpdateModhash GET to " + Constants.MODHASH_URL);
        }
        if (line.contains("USER_REQUIRED")) {
            throw new Exception("User session error: USER_REQUIRED");
        }

        Matcher modhashMatcher = MODHASH_PATTERN.matcher(line);
        if (modhashMatcher.find()) {
            modhash = modhashMatcher.group(1);
            if (StringUtils.isEmpty(modhash)) {
                // Means user is not actually logged in.
                return null;
            }
        } else {
            throw new Exception("No modhash found at URL " + Constants.MODHASH_URL);
        }

        if (Constants.LOGGING)
            Common.logDLong(TAG, line);

        if (Constants.LOGGING)
            Log.d(TAG, "modhash: " + modhash);
        return modhash;

    } catch (Exception e) {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (Exception e2) {
                if (Constants.LOGGING)
                    Log.e(TAG, "entity.consumeContent()", e);
            }
        }
        if (Constants.LOGGING)
            Log.e(TAG, "doUpdateModhash()", e);
        return null;
    }
}

From source file:net.pocketmine.server.ServerUtils.java

final public static void runServer() {
    // restoreOrCreateServerData();
    // restoreConfiguration("lighttpd.conf");
    // restoreConfiguration("php.ini");
    // restoreConfiguration("mysql.ini");
    setPermission();/*w  w w.  j a va 2 s. c om*/

    String[] serverCmd = { getAppDirectory() + "/php",
            // getAppDirectory() + "/php_data/PocketMine-MP.php"
            getDataDirectory() + "/PocketMine-MP.php" };

    try {
        serverProc = (new ProcessBuilder(serverCmd)).redirectErrorStream(true).start();
        stdout = serverProc.getInputStream();
        stdin = serverProc.getOutputStream();

        LogActivity.log("[PocketMine] Server is starting...");

        Thread tMonitor = new Thread() {
            public void run() {
                InputStreamReader reader = new InputStreamReader(stdout, Charset.forName("UTF-8"));
                BufferedReader br = new BufferedReader(reader);
                LogActivity.log("[PocketMine] Server was started.");

                while (isRunning()) {
                    try {
                        char[] buffer = new char[8192];
                        int size = 0;
                        while ((size = br.read(buffer, 0, buffer.length)) != -1) {
                            StringBuilder s = new StringBuilder();
                            for (int i = 0; i < size; i++) {
                                char c = buffer[i];
                                if (c == '\r') {
                                } //
                                else if (c == '\n' || c == '\u0007') {
                                    String line = s.toString();
                                    Log.d(TAG, line);

                                    String lineNoDate = "";
                                    int iof = line.indexOf(" ");
                                    if (iof != -1)
                                        lineNoDate = line.substring(iof + 1);
                                    if (lineNoDate.startsWith("[CMD] There are ") && requestPlayerRefresh
                                            && requestPlayerRefreshCount == -1) {

                                        try {
                                            String num = lineNoDate.substring("[CMD] There are ".length());
                                            num = num.substring(0, num.indexOf("/"));
                                            requestPlayerRefreshCount = Integer.parseInt(num);

                                            if (requestPlayerRefreshCount == 0) {
                                                HomeActivity.updatePlayerList(null);
                                                requestPlayerRefresh = false;
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } else if (lineNoDate.startsWith("[CMD] ") && requestPlayerRefresh
                                            && requestPlayerRefreshCount != -1) {

                                        String player = lineNoDate.substring(6);
                                        String[] players = player.split(", ");

                                        HomeActivity.updatePlayerList(players);

                                        requestPlayerRefresh = false;
                                    } else if (c == '\u0007' && line.startsWith("\u001B]0;")) {
                                        line = line.substring(4);
                                        System.out.println("[Stat] " + line);
                                        HomeActivity.setStats(getStat(line, "Online"), getStat(line, "RAM"),
                                                getStat(line, "U"), getStat(line, "D"), getStat(line, "TPS"));
                                    } else {
                                        LogActivity.log("[Server] " + (line.replace("&", "&amp;")
                                                .replace("<", "&lt;").replace(">", "&gt;")));

                                        if (line.contains("] logged in with entity id ")
                                                || line.contains("] logged out due to ")) {
                                            refreshPlayers();
                                        }
                                    }

                                    s = new StringBuilder();
                                } else {
                                    s.append(buffer[i]);
                                }
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            br.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                LogActivity.log("[PocketMine] Server was stopped.");
                HomeActivity.stopNotifyService();
                HomeActivity.hideStats();
            }

        };
        tMonitor.start();

        Log.i(TAG, "PHP is started");
    } catch (java.lang.Exception e) {
        Log.e(TAG, "Unable to start PHP", e);
        LogActivity.log("[PocketMine] Unable to start PHP.");
        HomeActivity.stopNotifyService();
        HomeActivity.hideStats();
        killProcessByName("php");
    }

    return;

}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

/**
 * Get data from HTTP POST method./*from   w  w  w  .ja  va2s  .c  om*/
 * 
 * This method uses
 * <ul>
 * <li>Connection timeout = 300000 (5 minutes)</li>
 * <li>Socket/Read timeout = 300000 (5 minutes)</li>
 * <li>Socket Read Buffer = 10485760 (10MB) to provide more space to read</li>
 * </ul>
 * -- in case the site is slow
 * 
 * @return
 * @throws MalformedURLException
 * @throws URISyntaxException
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws Exception
 */
public static String getPostData(String sourceUrl, String postString) throws MalformedURLException,
        URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException, Exception {
    String result = "";
    URL targetUrl = new URL(sourceUrl);

    /*
     * Create http parameter to set Connection timeout = 300000 Socket/Read
     * timeout = 300000 Socket Read Buffer = 10485760
     */
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 300000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 10485760);
    HttpConnectionParams.setSoTimeout(httpParams, 300000);

    // set the http param to the DefaultHttpClient
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    // create POST method and set the URL and POST data
    HttpPost post = new HttpPost(targetUrl.toURI());
    StringEntity entity = new StringEntity(postString, "UTF-8");
    post.setEntity(entity);
    logger.info("Execute the POST request with all input data");
    // Execute the POST request on the http client to get the response
    HttpResponse response = httpClient.execute(post, new BasicHttpContext());
    if (null != response && response.getStatusLine().getStatusCode() == 200) {
        HttpEntity httpEntity = response.getEntity();
        if (null != httpEntity) {
            long contentLength = httpEntity.getContentLength();
            logger.info("Content length: " + contentLength);
            // no data, if the content length is insufficient
            if (contentLength <= 0) {
                return "";
            }

            // read the response to String
            InputStream responseStream = httpEntity.getContent();
            if (null != responseStream) {
                BufferedReader reader = null;
                StringWriter writer = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(responseStream));
                    writer = new StringWriter();
                    int count = 0;
                    int size = 1024 * 1024;
                    char[] chBuff = new char[size];
                    while ((count = reader.read(chBuff, 0, size)) >= 0) {
                        writer.write(chBuff, 0, count);
                    }
                    result = writer.getBuffer().toString();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw ex;
                } finally {
                    IOUtils.closeQuietly(responseStream);
                    IOUtils.closeQuietly(reader);
                    IOUtils.closeQuietly(writer);
                }
            }
        }
    }
    logger.info("data read complete");
    return result;
}

From source file:com.nary.io.FileUtils.java

public static void readFile(File filePath, StringBuilder buffer) throws IOException {
    BufferedReader reader = null;
    Reader inreader = null;//from  w  ww.ja v  a  2  s  .  c om

    try {
        inreader = new FileReader(filePath);
        reader = new BufferedReader(inreader);

        char[] chars = new char[8096];
        int read;
        while ((read = reader.read(chars, 0, chars.length)) != -1) {
            buffer.append(chars, 0, read);
        }
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        if (inreader != null)
            try {
                inreader.close();
            } catch (IOException ignored) {
            }
    }
}

From source file:gate.util.Files.java

/** Get a resource from the GATE ClassLoader as a String.
  * @param encoding The encoding of the reader used to input the file
  * (may be null in which case the default encoding is used).
  * @param resourceName The resource to input.
  *///from w  w w  . j av  a  2s.com
public static String getResourceAsString(String resourceName, String encoding) throws IOException {
    InputStream resourceStream = getResourceAsStream(resourceName);
    if (resourceStream == null)
        return null;
    BufferedReader resourceReader;
    if (encoding == null) {
        resourceReader = new BomStrippingInputStreamReader(resourceStream);
    } else {
        resourceReader = new BomStrippingInputStreamReader(resourceStream, encoding);
    }
    StringBuffer resourceBuffer = new StringBuffer();

    int i;

    int charsRead = 0;
    final int size = 1024;
    char[] charArray = new char[size];

    while ((charsRead = resourceReader.read(charArray, 0, size)) != -1)
        resourceBuffer.append(charArray, 0, charsRead);

    while ((i = resourceReader.read()) != -1)
        resourceBuffer.append((char) i);

    resourceReader.close();
    return resourceBuffer.toString();
}