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(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:it.gmariotti.android.example.parser.json.ReadJsonActivity.java

private void readJson() {

    BufferedReader input = null;
    try {//w w  w  . j  ava2 s.c  o m
        input = new BufferedReader(new InputStreamReader(openFileInput("jsonfile")));
        String line;
        StringBuffer content = new StringBuffer();
        char[] buffer = new char[1024];
        int num;

        while ((num = input.read(buffer)) > 0) {
            content.append(buffer, 0, num);
        }

        MyObject myobj = JsonHelper.parse(content.toString());
        if (myobj != null) {
            // Update ui
            if (jsonView != null)
                jsonView.setText(myobj.toString());
            Log.i(TAG, myobj.toString());
        }

        /*
         * while ((line = input.readLine()) != null) { buffer.append(line +
         * eol); }
         */
    } catch (Exception e) {
        Log.e(TAG, "Error while reading ", e);
    }
}

From source file:it.gmariotti.android.example.parser.json.ReadJsonGsonActivity.java

private void readJson() {

    BufferedReader input = null;
    try {// w ww .ja va2s .  c o  m
        input = new BufferedReader(new InputStreamReader(openFileInput("jsonfile")));
        String line;
        StringBuffer content = new StringBuffer();
        char[] buffer = new char[1024];
        int num;

        while ((num = input.read(buffer)) > 0) {
            content.append(buffer, 0, num);
        }

        MyObject myobj = JsonHelper.parseGson(content.toString());
        if (myobj != null) {
            // Update ui
            if (jsonView != null)
                jsonView.setText(myobj.toString());
            Log.i(TAG, myobj.toString());
        }

        /*
         * while ((line = input.readLine()) != null) { buffer.append(line +
         * eol); }
         */
    } catch (Exception e) {
        Log.e(TAG, "Error while reading ", e);
    }
}

From source file:com.llkj.cm.restfull.network.NetworkConnection.java

/**
 * Transform an InputStream into a String
 * /*  w w  w.ja  v  a 2 s. co m*/
 * @param is InputStream
 * @return String from the InputStream
 * @throws IOException If a problem occurs while reading the InputStream
 */
private static String convertStreamToString(final InputStream is, final boolean isGzipEnabled, final int method,
        final int contentLength) throws IOException {
    InputStream cleanedIs = is;
    if (isGzipEnabled) {
        cleanedIs = new GZIPInputStream(is);
    }

    try {
        switch (method) {
        case METHOD_GET:
        case METHOD_DELETE: {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(cleanedIs));
            final StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();
        }
        case METHOD_POST:
        case METHOD_PUT: {
            int i = contentLength;
            if (i < 0) {
                i = 4096;
            }

            final Reader reader = new InputStreamReader(cleanedIs);
            final CharArrayBuffer buffer = new CharArrayBuffer(i);
            final char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }

            return buffer.toString();
        }
        default:
            return null;
        }
    } finally {
        cleanedIs.close();

        if (isGzipEnabled) {
            is.close();
        }
    }
}

From source file:com.norconex.importer.parser.impl.xfdl.XFDLParser.java

private void parse(BufferedReader reader, Writer out, ImporterMetadata metadata)
        throws IOException, ParserConfigurationException, SAXException {
    reader.mark(MAGIC_BASE64.length);/*from ww w  .j  a  v a  2s  .  c  o  m*/
    char[] signature = new char[MAGIC_BASE64.length];
    int num = reader.read(signature);
    reader.reset();
    if (num == -1) {
        return;
    }

    //--- Create XML DOM ---
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dom = null;
    if (Arrays.equals(signature, MAGIC_BASE64)) {
        // skip first line
        reader.readLine();

        // un-encode first
        byte[] compressedContent = Base64.decodeBase64(IOUtils.toString(reader));
        // deal with compression
        InputStream is = new GZIPInputStream(new ByteArrayInputStream(compressedContent));

        dom = docBuilder.parse(is);
        IOUtils.closeQuietly(is);
    } else {
        dom = docBuilder.parse(new InputSource(reader));
    }
    parseXML(dom, out, metadata);
}

From source file:playn.android.AndroidAssetManager.java

@Override
protected void doGetText(final String path, final ResourceCallback<String> callback) {
    try {/*from   ww w .  ja  va2 s . c om*/
        InputStream is = openAsset(path);
        try {
            StringBuilder fileData = new StringBuilder(1000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
            }
            reader.close();
            String text = fileData.toString();
            callback.done(text);
        } finally {
            is.close();
        }
    } catch (IOException e) {
        callback.error(e);
    }
}

From source file:playn.android.AndroidAssets.java

@Override
public String getTextSync(String path) throws Exception {
    InputStream is = openAsset(path);
    try {//from   ww w. j a v a 2 s  .c  o m
        StringBuilder fileData = new StringBuilder(1000);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    } finally {
        is.close();
    }
}

From source file:com.enonic.cms.core.http.HTTPService.java

public String getURL(String address, String encoding, int timeoutMs, int readTimeoutMs) {
    BufferedReader reader = null;
    try {/*from  w w w  .  j av  a 2  s .  c o m*/
        URLConnection urlConn = setUpConnection(address, timeoutMs, readTimeoutMs);
        reader = setUpReader(encoding, urlConn);
        StringBuffer sb = new StringBuffer(1024);
        char[] line = new char[1024];
        int charCount = reader.read(line);
        while (charCount > 0) {
            sb.append(line, 0, charCount);
            charCount = reader.read(line);
        }
        return sb.toString();

    } catch (Exception e) {
        String message = "Failed to get URL: \"" + address + "\": " + e.getMessage();
        LOG.warn(message);
    } finally {
        try {
            closeReader(reader);
        } catch (IOException ioe) {
            String message = "Failed to close reader stream: \"" + address + "\": " + ioe.getMessage();
            LOG.warn(message);
        }
    }

    return null;
}

From source file:com.gargoylesoftware.htmlunit.NoHttpResponseTest.java

@Override
public void run() {
    try {//  ww  w.  ja v a 2s  .c  o  m
        serverSocket_ = new ServerSocket(port_);
        started_.set(true);
        LOG.info("Starting listening on port " + port_);
        while (!shutdown_) {
            final Socket s = serverSocket_.accept();
            final BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            final CharBuffer cb = CharBuffer.allocate(5000);
            br.read(cb);
            cb.flip();
            final String in = cb.toString();
            cb.rewind();

            final RawResponseData responseData = getResponseData(in);

            if (responseData == null || responseData.getStringContent() == DROP_CONNECTION) {
                LOG.info("Closing impolitely in & output streams");
                s.getOutputStream().close();
            } else {
                final PrintWriter pw = new PrintWriter(s.getOutputStream());
                pw.println("HTTP/1.0 " + responseData.getStatusCode() + " " + responseData.getStatusMessage());
                for (final NameValuePair header : responseData.getHeaders()) {
                    pw.println(header.getName() + ": " + header.getValue());
                }
                pw.println();
                pw.println(responseData.getStringContent());
                pw.println();
                pw.flush();
                pw.close();
            }
            br.close();
            s.close();
        }
    } catch (final SocketException e) {
        if (!shutdown_) {
            LOG.error(e);
        }
    } catch (final IOException e) {
        LOG.error(e);
    } finally {
        LOG.info("Finished listening on port " + port_);
    }
}

From source file:com.orthancserver.OrthancConnection.java

public String ReadString(String uri) throws IOException {
    InputStream stream = OpenStream(uri);

    BufferedReader reader = null;
    try {//  www .ja v  a2s .  c o  m
        reader = new BufferedReader(new InputStreamReader(stream));

        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024 * 16];
        while ((read = reader.read(chars)) != -1) {
            buffer.append(chars, 0, read);
        }

        return buffer.toString();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:org.jbpm.designer.web.server.UUIDBasedRepositoryServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String actionParam = req.getParameter("action");
    String preProcessingParam = req.getParameter("pp");
    if (preProcessingParam == null) {
        preProcessingParam = "ReadOnlyService";
    }/* w  w w .j a  va2  s . c o  m*/
    if (actionParam != null && actionParam.equals("toXML")) {
        if (profile == null) {
            profile = _profileService.findProfile(req, profileName);
        }
        String json = req.getParameter("data");
        String xml = "";
        try {
            xml = _repository.toXML(json, profile, preProcessingParam);
        } catch (Exception e) {
            _logger.error("Error transforming to XML: " + e.getMessage());
        }
        StringWriter output = new StringWriter();
        output.write(xml);
        resp.setContentType("application/xml");
        resp.setCharacterEncoding("UTF-8");
        resp.setStatus(200);
        resp.getWriter().print(output.toString());
    } else if (actionParam != null && actionParam.equals("checkErrors")) {
        String retValue = "false";
        if (profile == null) {
            profile = _profileService.findProfile(req, profileName);
        }
        String json = req.getParameter("data");
        try {
            String xmlOut = profile.createMarshaller().parseModel(json, preProcessingParam);
            String jsonIn = profile.createUnmarshaller().parseModel(xmlOut, profile, preProcessingParam);
            if (jsonIn == null || jsonIn.length() < 1) {
                retValue = "true";
            }
        } catch (Throwable t) {
            retValue = "true";
            _logger.error("Exception parsing process: " + t.getMessage());
        }
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.setStatus(200);
        resp.getWriter().print(retValue);
    } else {
        BufferedReader reader = req.getReader();
        StringWriter reqWriter = new StringWriter();
        char[] buffer = new char[4096];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            reqWriter.write(buffer, 0, read);
        }

        String data = reqWriter.toString();
        try {
            JSONObject jsonObject = new JSONObject(data);

            String json = (String) jsonObject.get("data");
            String svg = (String) jsonObject.get("svg");
            String uuid = (String) jsonObject.get("uuid");
            boolean autosave = jsonObject.getBoolean("savetype");

            if (profile == null) {
                profile = _profileService.findProfile(req, profileName);
            }

            _repository.save(req, uuid, json, svg, profile, autosave);

        } catch (JSONException e1) {
            throw new ServletException(e1);
        }
    }
}