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:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * Response/*from  w  w  w . ja v a2 s .  c  o m*/
 * 
 * @param httpMethod
 * @return
 */
String getContent(HttpMethod httpMethod) {
    StringBuilder contentBuilder = new StringBuilder();
    if (isZipContent(httpMethod)) {
        // 
        InputStream is = null;
        GZIPInputStream gzin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = httpMethod.getResponseBodyAsStream();
            gzin = new GZIPInputStream(is);
            isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // 
            br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            int readlen = -1;
            while ((readlen = br.read(buffer, 0, 4096)) != -1) {
                contentBuilder.append(buffer, 0, readlen);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                isr.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                gzin.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                is.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    } else {
        // 
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
        } catch (Exception e) {
            log.error("", e);
        }
        if (null == content) {
            return null;
        }
        contentBuilder.append(content);
    }
    return contentBuilder.toString();
}

From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * ?Response??/* w w  w  .j a  va  2 s.c  o  m*/
 * 
 * @param httpMethod
 * @return
 */
String getContent(HttpMethod httpMethod) {
    StringBuilder contentBuilder = new StringBuilder();
    if (isZipContent(httpMethod)) {
        // ???
        InputStream is = null;
        GZIPInputStream gzin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = httpMethod.getResponseBodyAsStream();
            gzin = new GZIPInputStream(is);
            isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // ?????
            br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            int readlen = -1;
            while ((readlen = br.read(buffer, 0, 4096)) != -1) {
                contentBuilder.append(buffer, 0, readlen);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                isr.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                gzin.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                is.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    } else {
        // ???
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
        } catch (Exception e) {
            log.error("???", e);
        }
        if (null == content) {
            return null;
        }
        contentBuilder.append(content);
    }
    return contentBuilder.toString();
}

From source file:com.xmlcalabash.library.HttpRequest.java

private void readMultipartContent(TreeWriter tree, InputStream bodyStream, String boundary)
        throws IOException, SaxonApiException {
    MIMEReader reader = new MIMEReader(bodyStream, boundary);
    boolean done = false;
    while (reader.readHeaders()) {
        Header pctype = reader.getHeader("Content-Type");
        Header pclen = reader.getHeader("Content-Length");

        contentType = getHeaderValue(pctype);

        String charset = getContentCharset(pctype);
        String partType = getHeaderValue(pctype);
        InputStream partStream = null;

        if (pclen != null) {
            int len = Integer.parseInt(getHeaderValue(pclen));
            partStream = reader.readBodyPart(len);
        } else {/*w  w  w  .  j av a  2  s.c  o m*/
            partStream = reader.readBodyPart();
        }

        tree.addStartElement(XProcConstants.c_body);
        tree.addAttribute(_content_type, contentType);
        if (!xmlContentType(contentType) && !textContentType(contentType)) {
            tree.addAttribute(_encoding, "base64");
        }
        tree.startContent();

        if (xmlContentType(partType)) {
            BufferedReader preader = new BufferedReader(new InputStreamReader(partStream, charset));
            // Read it as XML
            tree.addSubtree(runtime.parse(new InputSource(preader)));
        } else if (textContentType(partType)) {
            BufferedReader preader = new BufferedReader(new InputStreamReader(partStream, charset));
            // Read it as text
            char buf[] = new char[bufSize];
            int len = preader.read(buf, 0, bufSize);
            while (len >= 0) {
                // I'm unsure about this. If I'm reading text and injecting it into XML,
                // I think I need to change CR/LF pairs (and CR not followed by LF) into
                // plain LFs.

                char fbuf[] = new char[bufSize];
                char flen = 0;
                for (int pos = 0; pos < len; pos++) {
                    if (buf[pos] == '\r') {
                        if (pos + 1 == len) {
                            // FIXME: Check for CR/LF pairs that cross a buffer boundary!
                            // Assume it's part of a CR/LF pair...
                        } else {
                            if (buf[pos + 1] == '\n') {
                                // nop
                            } else {
                                fbuf[flen++] = '\n';
                            }
                        }
                    } else {
                        fbuf[flen++] = buf[pos];
                    }
                }

                tree.addText(new String(fbuf, 0, flen));
                len = preader.read(buf, 0, bufSize);
            }
        } else {
            // Read it as binary
            byte bytes[] = new byte[bufSize];
            int pos = 0;
            int readLen = bufSize;
            int len = partStream.read(bytes, 0, bufSize);
            while (len >= 0) {
                pos += len;
                readLen -= len;
                if (readLen == 0) {
                    tree.addText(Base64.encodeBytes(bytes));
                    pos = 0;
                    readLen = bufSize;
                }

                len = partStream.read(bytes, pos, readLen);
            }

            if (pos > 0) {
                byte lastBytes[] = new byte[pos];
                System.arraycopy(bytes, 0, lastBytes, 0, pos);
                tree.addText(Base64.encodeBytes(lastBytes));
            }

            tree.addText("\n"); // FIXME: should we be doing this?
        }

        tree.addEndElement();
    }
}

From source file:org.apache.hadoop.fs.azure.NativeAzureFileSystemBaseTest.java

private String readString(FSDataInputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final int BUFFER_SIZE = 1024;
    char[] buffer = new char[BUFFER_SIZE];
    int count = reader.read(buffer, 0, BUFFER_SIZE);
    if (count > BUFFER_SIZE) {
        throw new IOException("Exceeded buffer size");
    }/*from  w ww. jav a2 s.  co  m*/
    inputStream.close();
    return new String(buffer, 0, count);
}

From source file:org.acmsl.commons.utils.io.FileUtils.java

/**
 * Reads a file and returns its contents.
 * @param file the file to be read.//from w ww  .j  a  v  a2s. co  m
 * @param charset the {@link Charset}.
 * @return the contents of the file.
 * @throws FileNotFoundException if the file is not found.
 * @throws SecurityException if the operation is forbidden because of
 * security manager settings.
 * @throws IOException if some I/O exception occurs.
 */
@NotNull
public char[] readFileContents(@NotNull final File file, @NotNull final Charset charset)
        throws SecurityException, IOException {
    @NotNull
    final char[] result;

    @Nullable
    FileInputStream t_fisFileStream = null;

    @Nullable
    InputStreamReader t_isFileReader = null;

    /*
     * To read file's contents it's better to use BufferedReader class.
     */
    @Nullable
    BufferedReader t_frPageBufferedReader = null;

    try {
        /*
         * Instantiate a FileReader object to read file's contents.
         */
        t_fisFileStream = new FileInputStream(file);

        t_isFileReader = new InputStreamReader(t_fisFileStream, charset);

        /*
         * To read file's contents it's better to use BufferedReader class.
         */
        t_frPageBufferedReader = new BufferedReader(t_isFileReader);

        if (file.length() > Integer.MAX_VALUE) {
            throw new IOException("File too large (" + file.length() + " bytes)");
        }

        /*
         * Next, I find out the necessary size of the array where file's
         * contents will be copied into.
         */
        result = new char[(int) file.length()];

        /*
         * Now I actually read the file, and fill the array.
         */
        t_frPageBufferedReader.read(result, 0, result.length);
    } finally {
        if (t_frPageBufferedReader != null) {
            try {
                t_frPageBufferedReader.close();
            } catch (final IOException cannotCloseStream) {
                LogFactory.getLog(FileUtils.class).warn("Cannot close file", cannotCloseStream);
            }
        }
        if (t_isFileReader != null) {
            try {
                t_isFileReader.close();
            } catch (final IOException cannotCloseStream) {
                LogFactory.getLog(FileUtils.class).warn("Cannot close file", cannotCloseStream);
            }
        }
        if (t_fisFileStream != null) {
            try {
                t_fisFileStream.close();
            } catch (final IOException cannotCloseStream) {
                LogFactory.getLog(FileUtils.class).warn("Cannot close file", cannotCloseStream);
            }
        }
    }
    return result;
}

From source file:net.gaast.giggity.Schedule.java

public void loadSchedule(String url_, Fetcher.Source source) throws IOException {
    url = url_;/*from  ww w .ja  v  a 2s. c  om*/

    id = null;
    title = null;

    allItems = new TreeMap<String, Schedule.Item>();
    tents = new LinkedList<Schedule.Line>();
    trackMap = null; /* Only assign if we have track info. */
    languages = new HashSet<>();

    firstTime = null;
    lastTime = null;

    dayList = null;
    curDay = null;
    curDayEnd = null;
    dayChange = new Date();
    dayChange.setHours(6);

    fullyLoaded = false;
    showHidden = false;

    icon = null;
    links = null;

    String head;
    Fetcher f = null;
    BufferedReader in;

    try {
        f = app.fetch(url, source);
        f.setProgressHandler(progressHandler);
        in = f.getReader();
        char[] headc = new char[detectHeaderSize];

        /* Read the first KByte (but keep it buffered) to try to detect the format. */
        in.mark(detectHeaderSize);
        in.read(headc, 0, detectHeaderSize);
        in.reset();

        head = new String(headc).toLowerCase();
    } catch (Exception e) {
        if (f != null)
            f.cancel();

        Log.e("Schedule.loadSchedule", "Exception while downloading schedule: " + e);
        e.printStackTrace();
        throw new LoadException("Network I/O problem: " + e);
    }

    /* Yeah, I know this is ugly, and actually reasonably fragile. For now it
     * just seems somewhat more efficient than doing something smarter, and
     * I want to avoid doing XML-specific stuff here already. */
    try {
        if (head.contains("<icalendar") && head.contains("<vcalendar")) {
            loadXcal(in);
        } else if (head.contains("<schedule") && head.contains("<conference")) {
            loadPentabarf(in);
        } else if (head.contains("<schedule") && head.contains("<line")) {
            loadDeox(in);
        } else if (head.contains("begin:vcalendar")) {
            loadIcal(in);
        } else {
            Log.d("head", head);
            throw new LoadException(app.getString(R.string.format_unknown));
        }
    } catch (LoadException e) {
        f.cancel();
        throw e;
    }

    Log.d("load", "Schedule has " + languages.size() + " languages");

    f.keep();

    if (title == null)
        if (id != null)
            title = id;
        else
            title = url;

    if (id == null)
        id = hashify(url);

    if (allItems.size() == 0) {
        throw new LoadException(app.getString(R.string.schedule_empty));
    }

    db = app.getDb();
    db.setSchedule(this, url, f.getSource() == Fetcher.Source.ONLINE);
    String md_json = db.getMetadata();
    if (md_json != null) {
        addMetadata(md_json);
    }

    /* From now, changes should be marked to go back into the db. */
    fullyLoaded = true;
}

From source file:utils.XMSEventListener.java

private void WaitEventThread() {

    //HttpGet - Container for the HTTP GET method.
    //  The HTTP GET method is defined in section 9.3 of RFC2616:
    //  The GET method means retrieve whatever information (in the form of an entity) 
    //  is identified by the Request-URI. If the Request-URI refers to a data-producing process, 
    //  it is the produced data which shall be returned as the entity in the response and not the 
    //  source text of the process, unless that text happens to be the output of the process.

    HttpGet httpget = new HttpGet(href + "?appid=" + AppID);

    //HttpResponse - After receiving and interpreting a request message, a server responds with an HTTP response message.
    //Response      = Status-Line
    //             *(( general-header
    //              | response-header
    //              | entity-header ) CRLF)
    //             CRLF
    //             [ message-body ]
    //http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
    HttpResponse httpResponse = null;/*from  w  w w.j  a  va  2 s  .  c om*/
    try {
        //Here you are issueing the GetRequest, to the provided host via the HttpClient and storing
        //  the response in the HpptResponse
        httpResponse = httpclient.execute(host, httpget);
    } catch (IOException ex) {

    }

    //We want to check that the get was successful by checking for a 2xx status code, in this case will be 200
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        System.out.println(
                "Error connecting to Event Stream - Status line = " + httpResponse.getStatusLine().toString());
        return;
    }

    //This GET differs from the typical get because the eventhander will not terminate the session on the receipt of 
    // this response.  Instead it will stay open and additional "chunks" of data well be sent in for each event
    HttpEntity httpentity = httpResponse.getEntity();
    InputStream instream = null;

    try {
        //What we will be doing is get access to the InputStream via the httpentity we then assign this to the InputStream

        instream = httpentity.getContent();
    } catch (IOException ex) {
        Logger.getLogger(XMSEventListener.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalStateException ex) {
        Logger.getLogger(XMSEventListener.class.getName()).log(Level.SEVERE, null, ex);
    }

    InputStreamReader isr;
    BufferedReader reader;
    String xmlString = null;

    /**
         * Setting up input stream to read from the socket connection..  This StreamReader
         * is setup to point to the input stream from the GetRequest that is left open
         */
    isr = new InputStreamReader(instream);
    reader = new BufferedReader(isr);
    int i = 0;
    xmlString = "";

    /********************************************************************
     * The HTTP Connection remains open.
     * Use a BufferedReader to grab data as it comes across the wire
     ********************************************************************/
    String xmlStringPrime = null;
    String xmlStringCleaned;

    try {

        for (;;) {
            if (start == false) {
                System.out.println("Finalizou thread");
                return;
            }
            //While the reader is empty it will block here
            String line = reader.readLine();
            // We are reading in the first line of the message as this will contain 
            // the legth of the message
            // FOR details on this look at Event Streamin section of the
            // http://www.dialogic.com/webhelp/XMS/2.3/XMS_RESTfulAPIUser.pdf

            //System.out.println("**New Message **\n  Message size is "+line);

            //This block of code is here in case the inbound message is devided into
            // multiple sections.  This code will keep reading till the entire
            // length above is received
            int ChunkSize = Integer.parseInt(line, 16);
            char buff[] = new char[ChunkSize];
            if (ChunkSize <= 0)
                break;

            xmlString = "";
            int readsize = 0;

            while (readsize < ChunkSize) {
                readsize = reader.read(buff, readsize, ChunkSize - readsize) + readsize;
                //System.out.println("Reading "+readsize+" of "+ChunkSize);

            }
            xmlString += new String(buff);
            //System.out.println("****** Message Contents *******\n"+xmlString);

            //Here we will mark ourselves as updated and then Send the XMS event received
            // to any of the Observers for processing
            setChanged();
            notifyObservers(xmlString);
        }

    } catch (IOException ex) {
        Logger.getLogger(XMSEventListener.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:forseti.JUtil.java

/**
 * Lee un nmero de caracteres de un BufferedReader y los escribe en
 * un array de bytes a partir de una posicin dada
 * @param sourceTextReader BufferedReader del que leer caracteres.
 * @param target byte[] donde se escribiran los caracteres ledos
 * @param start int posicin a partir de la cual se escribe en el array.
 * @param count int mximo de caracteres a leer del buffer.
 * @return int nmero de caracteres ledos. -1 s no se leyo ningn caracter
 *///from   w  w  w.ja v  a 2 s. com
public static synchronized int ReadInput(java.io.BufferedReader sourceTextReader, short[] target, int start,
        int count) {
    // Devuelve 0 bytes si no hay suficiente espacio
    if (target.length == 0)
        return 0;

    char[] charArray = new char[target.length];
    int bytesRead;

    try {
        bytesRead = sourceTextReader.read(charArray, start, count);
    } catch (IOException ioex) {
        throw new EncodingFailedException("Fallo de lectura en el archivo data");
    }

    // Devuelve -1 si EOF
    if (bytesRead == 0)
        return -1;

    for (int index = start; index < start + bytesRead; index++)
        target[index] = (short) charArray[index];

    return bytesRead;
}

From source file:org.kepler.ssh.LocalExec.java

public int executeCmd(String command, OutputStream streamOut, OutputStream streamErr, String thirdPartyTarget)
        throws ExecException {
    _commandArr[_commandCount] = command;

    Runtime rt = Runtime.getRuntime();
    Process proc;/* ww  w . j  a va  2s  . c om*/

    // get the pwd/passphrase to the third party (and perform authentication
    // if not yet done)
    String pwd = SshSession.getPwdToThirdParty(thirdPartyTarget);

    try {
        proc = rt.exec(_commandArr);
    } catch (Exception ex) {
        //ex.printStackTrace();
        throw new ExecException("Cannot execute cmd ** : " + _commandArr[_commandCount] + ex);
    }

    // System.out.println("%%% Process started");

    // the streams from the process: stdout and stderr
    BufferedReader out_in = new BufferedReader(new InputStreamReader(proc.getInputStream())); // stdout
    BufferedReader err_in = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // stderr

    // the streams towards the caller: stdout and stderr
    BufferedWriter out_out = new BufferedWriter(new OutputStreamWriter(streamOut));
    BufferedWriter err_out = new BufferedWriter(new OutputStreamWriter(streamErr));

    BufferedWriter proc_in = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); // stdin

    String line; // Temp for each line of output.
    int exitVal = -32766;
    boolean readOut = true;
    boolean readErr = true;
    boolean finished = false;
    boolean checkForPwd = (pwd != null);
    char c[] = new char[256];
    int charsRead;

    // variables for the timeout checking
    long start = System.currentTimeMillis();
    long current = 0;
    long maxtime = timeout * 1000L;

    while (!finished) { // will stop when the process terminates or after
        // timeout
        // check the status of the process
        try {
            exitVal = proc.exitValue();
            finished = true; // process terminated so exit this loop after
                             // reading the buffers
        } catch (IllegalThreadStateException ex) {
            // process not yet terminated so we go further
        }

        // read stdout
        if (readOut) {
            try {
                while (out_in.ready()) {
                    charsRead = out_in.read(c, 0, 256);
                    out_out.write(c, 0, charsRead);

                    // System.out.println("%%% "+ new String(c, 0,
                    // charsRead));
                    /*
                     * try { proc_in.write("Anyadat\n", 0, 8); // send the
                     * password proc_in.flush(); } catch (Exception ex) {
                     * System.out.println("### "+ex);
                     * 
                     * }
                     */
                    if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) {

                        // System.out.println("%%% Found password request");

                        out_out.flush(); // so you may see the request on
                                         // stdout already
                        proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send
                        // the
                        // password
                        proc_in.flush();
                        log.info("Sent password to third party.");
                        checkForPwd = false; // even if it's wrong, do not
                                             // do it again
                    }
                    if (timeoutRestartOnStdout)
                        start = System.currentTimeMillis(); // restart
                    // timeout timer
                }
            } catch (IOException ioe) {
                log.error("<IOException> when reading the stdout: " + ioe + "</IOException>");
                readOut = false;
            }
        }

        // read stderr
        if (readErr) {
            try {
                while (err_in.ready()) {
                    charsRead = err_in.read(c, 0, 256);
                    err_out.write(c, 0, charsRead);
                    System.out.println("### " + new String(c, 0, charsRead));
                    if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) {

                        System.out.println("### Found password request");

                        out_out.flush(); // so you may see the request on
                                         // stdout already
                        proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send
                        // the
                        // password
                        proc_in.flush();
                        log.info("Sent password to third party.");
                        checkForPwd = false; // even if it's wrong, do not
                                             // do it again
                    }
                    if (timeoutRestartOnStderr)
                        start = System.currentTimeMillis(); // restart
                    // timeout timer
                }
            } catch (IOException ioe) {
                log.error("<IOException> when reading the stderr: " + ioe + "</IOException>");
                readErr = false;
            }
        }

        // sleep a bit to not overload the system
        if (!finished)
            try {
                java.lang.Thread.sleep(100);
            } catch (InterruptedException ex) {
            }

        // check timeout
        current = System.currentTimeMillis();
        if (timeout > 0 && maxtime < current - start) {
            log.error("Timeout: " + timeout + "s elapsed for command " + command);
            proc.destroy();
            throw new ExecTimeoutException(command);
            // exitVal = timeoutErrorCode;
            // finished = true;
        }

    }

    try {
        // flush to caller
        out_out.flush();
        err_out.flush();
        // close streams from/to child process
        out_in.close();
        err_in.close();
        proc_in.close();
    } catch (IOException ex) {
        log.error("Could not flush output streams: " + ex);
    }

    // System.out.println("ExitValue: " + exitVal);
    return exitVal;

}