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:oeg.licensius.service.ServiceCommons.java

/**
 * */*from  w  w w.j a  va2 s  . c  o  m*/
 * Obtains the body from a HTTP request. Period. No more, no less.
 */
public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }
    body = stringBuilder.toString();
    return body;
}

From source file:de.Keyle.MyPet.api.Util.java

public static String readFileAsString(String filePath) throws java.io.IOException {
    StringBuilder fileData = new StringBuilder(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    char[] buf = new char[1024];
    int numRead;//  w  w  w.  j a v a 2  s . c o m
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1024];
    }
    reader.close();
    return fileData.toString();
}

From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java

public static String loadStringFromDiskFile(String fullPath, boolean existenceChecked)
        throws UsenetReaderException, IOException {

    String ret = null;//from   w w w  .  j  a  va 2s .  c om
    File f = new File(fullPath);

    if (!existenceChecked && !f.exists()) {
        throw new UsenetReaderException("File could not be found in " + fullPath);
    }

    char[] buff = new char[(int) f.length()];
    BufferedReader in = null;

    try {
        FileReader freader = new FileReader(fullPath);
        in = new BufferedReader(freader);
        in.read(buff);
        ret = new String(buff);
    } finally {
        if (in != null)
            in.close();
    }

    return ret;
}

From source file:net.sourceforge.users.dragomerlin.vcs2icsCalendarConverter.ConvertSingleFile.java

private static String readPossibleMultiline(String fieldContent, BufferedReader inStream) throws IOException {
    char[] buf = new char[1];
    boolean multilineFound = false;
    do {/*  w  ww  . j av  a2 s. co  m*/
        inStream.mark(1);
        int res = inStream.read(buf);
        if (res == -1) {
            throw new IOException("Error while reading multiline: EOF.");
        }

        if (buf[0] == ' ') {
            multilineFound = true;
            String line = inStream.readLine();
            fieldContent += line;
        } else {
            multilineFound = false;
        }
    } while (multilineFound);
    inStream.reset();
    return fieldContent;
}

From source file:com.fpmislata.clientecategoriasjson.ClienteClienteTest.java

private static String readObject(HttpResponse httpResponse) throws IOException {
    BufferedReader bufferedReader = null;
    try {//  w w w  .  j a  va2  s.c  o  m
        bufferedReader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        StringBuffer buffer = new StringBuffer();
        char[] dataLength = new char[1024];
        int read;
        while ((read = bufferedReader.read(dataLength)) != -1) {
            buffer.append(dataLength, 0, read);
        }
        System.out.println(buffer.toString());
        return buffer.toString();
    } catch (Exception e) {
        throw e;
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
    }
}

From source file:org.apache.airavata.registry.tool.DBMigrator.java

protected static InputStream readFile(File file) {
    StringBuilder fileContentsBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {/*w  w  w.ja va  2 s. c  o  m*/
        char[] buffer = new char[32767];
        bufferedReader = new BufferedReader(new FileReader(file));
        int read = 0;

        do {
            read = bufferedReader.read(buffer);
            if (read > 0) {
                fileContentsBuilder.append(buffer, 0, read);
            }
        } while (read > 0);
    } catch (Exception e) {
        logger.error("Failed to read file " + file.getPath(), e);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                logger.error("Unable to close BufferedReader for " + file.getPath(), e);
            }
        }
    }
    System.out.println(fileContentsBuilder.toString());
    InputStream is = new ByteArrayInputStream(fileContentsBuilder.toString().getBytes());

    return is;
}

From source file:eu.liveandgov.ar.utilities.RestClient.java

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = null;
    try {//from  ww w .j a  v  a 2 s  .com
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        Log.e("RestClient", "Can not read from InputStream");
    }
    StringBuilder sb = new StringBuilder();

    char[] buf = new char[1];

    try {
        while (reader.read(buf) != -1)
            sb.append(buf);
    } catch (IOException e) {
        Log.e("RestClient", "IO Exception");
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e("RestClient", "IO Exception B");
        }
    }
    return sb.toString();
}

From source file:com.google.gsa.valve.modules.utils.HTTPAuthZProcessor.java

/**
 * Reads the file in blocks for non-HTML documents
 * // ww  w  .j av  a 2  s . c  o m
 * @param input the input reader
 * 
 * @return the content block
 * 
 * @throws IOException
 */
public static String readFully(Reader input) throws IOException {

    String resultStr = null;

    BufferedReader bufferedReader = input instanceof BufferedReader ? (BufferedReader) input
            : new BufferedReader(input);
    StringBuffer result = new StringBuffer();
    char[] buffer = new char[BUFFER_BLOCK_SIZE];
    int charsRead;
    while ((charsRead = bufferedReader.read(buffer)) != -1) {
        result.append(buffer, 0, charsRead);
    }

    resultStr = result.toString();

    //protection
    bufferedReader = null;
    result = null;
    buffer = null;

    return resultStr;
}

From source file:com.googlecode.talkingrssreader.talkingrss.ReaderHttp.java

private static String readAll(InputStream stream) throws NetworkException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 16 * 1024);
    StringWriter sw = new StringWriter();
    char[] buf = new char[32 * 1024];
    try {// w ww .  j  a va  2  s  .c o  m
        while (true) {
            int len = reader.read(buf);
            if (len == -1)
                break;
            sw.write(buf, 0, len);
        }
    } catch (IOException e) {
        throw new NetworkException(e);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
        }
    }
    return sw.toString();
}

From source file:eu.interedition.collatex.tools.CollationPipe.java

public static void start(CommandLine commandLine) throws Exception {
    List<SimpleWitness> witnesses = null;
    Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT;
    Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS;
    Comparator<Token> comparator = new EqualityTokenComparator();
    CollationAlgorithm collationAlgorithm = null;
    boolean joined = true;

    final String[] witnessSpecs = commandLine.getArgs();
    final InputStream[] inputStreams = new InputStream[witnessSpecs.length];
    for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) {
        try {/*  w w w.j  a  v  a  2  s  .c om*/
            inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]);
        } catch (MalformedURLException urlEx) {
            throw new ParseException("Invalid resource: " + witnessSpecs[wc]);
        }
    }

    if (inputStreams.length < 1) {
        throw new ParseException("No input resource(s) given");
    } else if (inputStreams.length < 2) {
        try (InputStream inputStream = inputStreams[0]) {
            final SimpleCollation collation = JsonProcessor.read(inputStream);
            witnesses = collation.getWitnesses();
            collationAlgorithm = collation.getAlgorithm();
            joined = collation.isJoined();
        }
    }

    final String script = commandLine.getOptionValue("s");
    try {
        final PluginScript pluginScript = (script == null
                ? PluginScript.read("<internal>", new StringReader(""))
                : PluginScript.read(argumentToInput(script)));

        tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer);
        normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer);
        comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator);
    } catch (IOException e) {
        throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage());
    }

    switch (commandLine.getOptionValue("a", "").toLowerCase()) {
    case "needleman-wunsch":
        collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator);
        break;
    case "medite":
        collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR);
        break;
    case "gst":
        collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2);
        break;
    default:
        collationAlgorithm = Optional.ofNullable(collationAlgorithm)
                .orElse(CollationAlgorithmFactory.dekker(comparator));
        break;
    }

    if (witnesses == null) {
        final Charset inputCharset = Charset
                .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name()));
        final boolean xmlMode = commandLine.hasOption("xml");
        final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath()
                .compile(commandLine.getOptionValue("xp", "//text()"));

        witnesses = new ArrayList<>(inputStreams.length);
        for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) {
            try (InputStream stream = inputStreams[wc]) {
                final String sigil = "w" + (wc + 1);
                if (!xmlMode) {
                    final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(stream, inputCharset));
                    final StringWriter writer = new StringWriter();
                    final char[] buf = new char[1024];
                    while (reader.read(buf) != -1) {
                        writer.write(buf);
                    }
                    witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer));
                } else {
                    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder();
                    final Document document = documentBuilder.parse(stream);
                    document.normalizeDocument();

                    final SimpleWitness witness = new SimpleWitness(sigil);
                    final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document,
                            XPathConstants.NODESET);
                    final List<Token> tokens = new ArrayList<>(tokenNodes.getLength());
                    for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                        final String tokenText = tokenNodes.item(nc).getTextContent();
                        tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText)));
                    }
                    witness.setTokens(tokens);
                    witnesses.add(witness);
                }
            }
        }
    }

    final VariantGraph variantGraph = new VariantGraph();
    collationAlgorithm.collate(variantGraph, witnesses);

    if (joined && !commandLine.hasOption("t")) {
        VariantGraph.JOIN.apply(variantGraph);
    }

    final String output = commandLine.getOptionValue("o", "-");
    final Charset outputCharset = Charset
            .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name()));
    final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase();

    try (PrintWriter out = argumentToOutput(output, outputCharset)) {
        final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph);
        if ("csv".equals(outputFormat)) {
            serializer.toCsv(out);
        } else if ("dot".equals(outputFormat)) {
            serializer.toDot(out);
        } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) {
            XMLStreamWriter xml = null;
            try {
                xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                xml.writeStartDocument(outputCharset.name(), "1.0");
                if ("graphml".equals(outputFormat)) {
                    serializer.toGraphML(xml);
                } else {
                    serializer.toTEI(xml);
                }
                xml.writeEndDocument();
            } catch (XMLStreamException e) {
                throw new IOException(e);
            } finally {
                if (xml != null) {
                    try {
                        xml.close();
                    } catch (XMLStreamException e) {
                        // ignored
                    }
                }
            }
        } else {
            JsonProcessor.write(variantGraph, out);
        }
    }
}