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 int read(char cbuf[]) throws IOException 

Source Link

Document

Reads characters into an array.

Usage

From source file:PrintTextWrapPagetation.java

void menuOpen() {
    final String textString;
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setFilterExtensions(new String[] { "*.java", "*.*" });
    String name = dialog.open();//from   w ww  .  ja  v  a  2s.  c o m
    if ((name == null) || (name.length() == 0))
        return;

    try {
        File file = new File(name);
        FileInputStream stream = new FileInputStream(file.getPath());
        try {
            Reader in = new BufferedReader(new InputStreamReader(stream));
            char[] readBuffer = new char[2048];
            StringBuffer buffer = new StringBuffer((int) file.length());
            int n;
            while ((n = in.read(readBuffer)) > 0) {
                buffer.append(readBuffer, 0, n);
            }
            textString = buffer.toString();
            stream.close();
        } catch (IOException e) {
            MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
            box.setMessage("Error reading file:\n" + name);
            box.open();
            return;
        }
    } catch (FileNotFoundException e) {
        MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
        box.setMessage("File not found:\n" + name);
        box.open();
        return;
    }
    text.setText(textString);
}

From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

protected String readFileFromNode(Node fileNode)
        throws IOException, ValueFormatException, PathNotFoundException, RepositoryException {
    CharArrayWriter writer = null;
    InputStream in = null;//from  ww w  . j a  va 2s .c  o  m
    Reader reader = null;
    try {
        in = fileNode.getNode(JcrConstants.JCR_CONTENT).getProperty(JcrConstants.JCR_DATA).getStream();
        writer = new CharArrayWriter();
        reader = new InputStreamReader(in);
        char[] buffer = new char[8];
        int c = 0;
        while ((c = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, c);
        }
        return new String(writer.toCharArray());
    } catch (IOException ioex) {
        return null;
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (in != null) {
            in.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:gtu.youtube.JavaYoutubeVideoUrlHandler.java

private String getStringFromInputStream(String encoding, InputStream instream)
        throws UnsupportedEncodingException, IOException {
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {/*  w  w  w .  j  a v a  2  s . co  m*/
        Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        instream.close();
    }
    String result = writer.toString();
    return result;
}

From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java

public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
    if (reader == null) {
        setNull(parameterIndex, 0);/*from   w  ww.ja  v  a 2 s. c om*/
        return;
    }
    char[] c = new char[length];
    int read;
    try {
        if ((read = reader.read(c)) != length) {
            throw new SQLException("CharacterStream read length:" + read);
        }
    } catch (IOException e) {
        throw new SQLException(e);
    }
    setString(parameterIndex, new String(c));
}

From source file:it.infn.ct.aleph_portlet.java

public static String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {/* w  w w  . java  2  s. co  m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);

            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.webcohesion.ofx4j.io.BaseOFXReader.java

/**
 * Parse the reader, including the headers.
 *
 * @param reader The reader./*ww w .j a v a2 s.c  o m*/
 */
public void parse(Reader reader) throws IOException, OFXParseException {
    //make sure we're buffering...
    reader = new BufferedReader(reader);

    StringBuilder header = new StringBuilder();
    final char[] firstElementStart = getFirstElementStart();
    final char[] buffer = new char[firstElementStart.length];
    reader.mark(firstElementStart.length);
    int ch = reader.read(buffer);
    while ((ch != -1) && (!Arrays.equals(buffer, firstElementStart))) {
        if (!contains(buffer, '<')) {
            //if the buffer contains a '<', then we might already have marked the beginning.
            reader.mark(firstElementStart.length);
        }
        ch = reader.read();
        char shifted = shiftAndAppend(buffer, (char) ch);
        header.append(shifted);
    }

    if (ch == -1) {
        throw new OFXParseException("Invalid OFX: no root <OFX> element!");
    } else {
        Matcher matcher = OFX_2_PROCESSING_INSTRUCTION_PATTERN.matcher(header);
        if (matcher.find()) {
            if (LOG.isInfoEnabled()) {
                LOG.info("Processing OFX 2 header...");
            }

            processOFXv2Headers(matcher.group(1));
            reader.reset();
            parseV2FromFirstElement(reader);
        } else {
            LOG.info("Processing OFX 1 headers...");
            processOFXv1Headers(header.toString());
            reader.reset();
            parseV1FromFirstElement(reader);
        }
    }
}

From source file:me.xiaopan.android.gohttp.JsonHttpResponseHandler.java

private String toString(HttpRequest httpRequest, final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return "";
    }// www.ja v a  2 s.co m
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int contentLength = (int) entity.getContentLength();
    if (contentLength < 0) {
        contentLength = 4096;
    }
    String charset = StringHttpResponseHandler.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    Reader reader = new InputStreamReader(inputStream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        char[] tmp = new char[1024];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, readLength);
            completedLength += readLength;
            if (progressListener != null && !httpRequest.isCanceled()
                    && (completedLength >= (callbackNumber + 1) * averageLength
                            || completedLength == contentLength)) {
                callbackNumber++;
                new HttpRequestHandler.UpdateProgressRunnable(httpRequest, contentLength, completedLength)
                        .execute();
            }
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

From source file:com.bigdata.gom.TestRemoteGOM.java

void print(final URL n3) throws IOException {
    if (log.isInfoEnabled()) {
        InputStream in = n3.openConnection().getInputStream();
        Reader reader = new InputStreamReader(in);
        try {//  w w w .  j  a va 2 s.  co m
            char[] buf = new char[256];
            int rdlen = 0;
            while ((rdlen = reader.read(buf)) > -1) {
                if (rdlen == 256)
                    System.out.print(buf);
                else
                    System.out.print(new String(buf, 0, rdlen));
            }
        } finally {
            reader.close();
        }
    }
}

From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java

@Override
public void run() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    if (useAuthentication) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(remoteUsername, remotePassword));
    }//from ww  w  . j  a  v a 2  s.c o m

    HttpGet get = new HttpGet(remoteUrl);

    try {
        super.sendInitMessage(R.string.downloading);

        HttpResponse response = client.execute(get);
        Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " "
                + isGoodResponse(response.getStatusLine().getStatusCode()));
        if (isGoodResponse(response.getStatusLine().getStatusCode())) {
            HttpEntity entity = response.getEntity();

            InputStream instream = entity.getContent();
            if (instream == null) {
                super.sendErrorMessage(R.string.couldnotConnectToRemoteserver);
                return;
            }
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                super.sendErrorMessage(R.string.remoteFileTooLarge);
                return;
            }
            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            String charset = EntityUtils.getContentCharSet(entity);
            if (charset == null) {
                charset = encoding;
            }
            if (charset == null) {
                charset = HTTP.DEFAULT_CONTENT_CHARSET;
            }
            Reader reader = new InputStreamReader(instream, charset);
            CharArrayBuffer buffer = new CharArrayBuffer(i);

            super.sendMaximumMessage(i);

            try {
                char[] tmp = new char[1024];
                int l;
                while ((l = reader.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                    super.sendProgressMessage(buffer.length());
                }
            } finally {
                reader.close();
            }

            super.sendFinishedMessage(buffer.toString());
        } else {
            int errorMsg = R.string.couldnotConnectToRemoteserver;
            if (isAccessDenied(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.accessDenied;
            } else if (isFileNotFound(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.remoteFileNotFound;
            }
            super.sendErrorMessage(errorMsg);
        }
    } catch (UnknownHostException e) {
        super.sendErrorMessage(R.string.unknownHostException, e);
        Log.e(LOG_TAG, "Error occured", e);
    } catch (Throwable e) {
        super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e);
        Log.e(LOG_TAG, "Error occured", e);
    }

    finally {
        client.getConnectionManager().shutdown();
    }
}