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() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static Pair<String, String> getPageDataOldImpl(URL url, int timeout) {
    StringBuffer sb = new StringBuffer();
    String charset = null;/*www  .jav  a2s.  c om*/
    try {
        URLConnection connection = url.openConnection();
        if (timeout >= 0)
            connection.setConnectTimeout(timeout);
        InputStream is = connection.getInputStream();
        final String type = connection.getContentType();
        if (type != null) {
            final String[] parts = type.split(";");
            for (int i = 1; i < parts.length && charset == null; i++) {
                final String t = parts[i].trim();
                final int index = t.toLowerCase().indexOf("charset=");
                if (index != -1)
                    charset = t.substring(index + 8);
            }
        }
        InputStreamReader isr = null;
        if (charset != null)
            isr = new InputStreamReader(is, charset);
        else
            isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        int read = 0;
        while ((read = br.read()) != -1) {
            sb.append((char) read);
        }
        br.close();
        isr.close();
        is.close();
    } catch (Exception e) {
        Debug.error(e);
    }
    return new Pair<String, String>(sb.toString(), charset);
}

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

@Nonnull
@MustNotContainNull/*w  w  w  .  jav  a 2  s  .  co  m*/
public static String[] readWholeTextFileIntoArray(@Nonnull final File file, @Nullable final String encoding,
        @Nullable final AtomicBoolean endedByNextLine) throws IOException {
    checkFile(file);

    final String enc = encoding == null ? "UTF8" : encoding;

    final BufferedReader srcBufferedReader = PreprocessorUtils.makeFileReader(file, enc, (int) file.length());
    final List<String> strContainer = new ArrayList<String>(1024);
    try {
        final StringBuilder buffer = new StringBuilder();

        boolean stringEndedByNextLine = false;

        boolean meetCR = false;

        while (true) {
            final int chr = srcBufferedReader.read();
            if (chr < 0) {
                break;
            }

            switch (chr) {
            case '\n': {
                stringEndedByNextLine = true;
                strContainer.add(buffer.toString());
                buffer.setLength(0);
                meetCR = false;
            }
                break;
            case '\r': {
                if (meetCR) {
                    buffer.append((char) chr);
                } else {
                    stringEndedByNextLine = false;
                    meetCR = true;
                }
            }
                break;
            default: {
                if (meetCR) {
                    buffer.append('\r');
                }
                meetCR = false;
                stringEndedByNextLine = false;
                buffer.append((char) chr);
            }
                break;
            }
        }

        if (buffer.length() != 0) {
            strContainer.add(buffer.toString());
            buffer.setLength(0);
        }

        if (endedByNextLine != null) {
            endedByNextLine.set(stringEndedByNextLine);
        }
    } finally {
        srcBufferedReader.close();
    }

    return strContainer.toArray(new String[strContainer.size()]);
}

From source file:org.opendatakit.utilities.LocalizationUtils.java

private static synchronized void loadTranslations(String appName, String tableId) throws IOException {
    if (savedAppName != null && !savedAppName.equals(appName)) {
        clearTranslations();//  w  w  w  .  j ava 2 s .  c  o m
    }
    savedAppName = appName;
    TypeReference<HashMap<String, Object>> ref = new TypeReference<HashMap<String, Object>>() {
    };
    if (commonDefinitions == null) {
        File commonFile = new File(ODKFileUtils.getCommonDefinitionsFile(appName));
        if (commonFile.exists() && commonFile.isFile()) {
            InputStream stream = null;
            BufferedReader reader = null;
            String value;
            try {
                stream = new FileInputStream(commonFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    ch = reader.read();
                }

                StringBuilder b = new StringBuilder();
                b.append((char) ch);
                ch = reader.read();
                while (ch != -1) {
                    b.append((char) ch);
                    ch = reader.read();
                }
                reader.close();
                stream.close();
                value = b.toString().trim();
                if (value.endsWith(";")) {
                    value = value.substring(0, value.length() - 1).trim();
                }

            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }

            try {
                commonDefinitions = ODKFileUtils.mapper.readValue(value, ref);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalStateException("Unable to read commonDefinitions.js file");
            }
        }
    }

    if (tableId != null) {
        File tableFile = new File(ODKFileUtils.getTableSpecificDefinitionsFile(appName, tableId));
        if (!tableFile.exists()) {
            tableSpecificDefinitionsMap.remove(tableId);
        } else {
            // assume it is current if it exists
            if (tableSpecificDefinitionsMap.containsKey(tableId)) {
                return;
            }
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                stream = new FileInputStream(tableFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                reader.mark(1);
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    reader.mark(1);
                    ch = reader.read();
                }
                reader.reset();
                Map<String, Object> tableSpecificTranslations = ODKFileUtils.mapper.readValue(reader, ref);
                if (tableSpecificTranslations != null) {
                    tableSpecificDefinitionsMap.put(tableId, tableSpecificTranslations);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }
        }
    }
}

From source file:org.jcryptool.commands.core.HelpCommand.java

/**
 * reads the current value from an input stream
 *
 * @param in the input stream//  w ww.  j ava2s.c om
 */
private static String InputStreamToString(InputStream in) {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(in, IConstants.UTF8_ENCODING));
    } catch (UnsupportedEncodingException ex) {
        reader = new BufferedReader(new InputStreamReader(in));
        LogUtil.logError(CommandsCorePlugin.PLUGIN_ID, ex);
    }

    StringBuffer myStrBuf = new StringBuffer();
    int charOut = 0;
    String output = ""; //$NON-NLS-1$
    try {
        while ((charOut = reader.read()) != -1) {
            myStrBuf.append(String.valueOf((char) charOut));
        }
    } catch (IOException e) {
        LogUtil.logError(CommandsCorePlugin.PLUGIN_ID, e);
    }
    output = myStrBuf.toString();
    return output;
}

From source file:jeplus.EPlusWinTools.java

/**
 * /*  ww w.  java 2 s  .  co m*/
 * @param xesoview
 * @param esofile
 * @return the exit code
 */
public static int runXEsoView(String xesoview, String esofile) {

    try {
        // Run EP-Macro executable
        String CmdLine = xesoview + " " + esofile;
        Process EPProc = Runtime.getRuntime().exec(CmdLine);

        BufferedReader ins = new BufferedReader(new InputStreamReader(EPProc.getInputStream()));

        int res = ins.read();
        if (res != -1) {
            do {
                res = ins.read();
            } while (res != -1);
            ins.close();
        }

        EPProc.waitFor();

    } catch (IOException | InterruptedException ex) {
        logger.error("", ex);
    }

    // Return Radiance exit value
    return 0;
}

From source file:autohit.common.Utils.java

/**
 *  Merge a file with properties.  It will overwrite an existing file.
 *  This is not exactly FAST.//from   ww w .  j av a2s .c o  m
 * @param source source file
 * @param dest destination file
 * @param props properties that are candidates for substitution
 * @return string containing errors or messages
 */
public static String merge(String source, String dest, ExtendedProperties props) {

    int state = STATE_FRESH;
    BufferedReader inBR = null;
    BufferedWriter outT = null;
    int workingC;
    StringBuffer cBuf = null;
    String theVar = null;
    String ts = null;
    StringBuffer messages = new StringBuffer();
    String overwrite = " ";

    // Read and fix
    try {
        // Clear an existing file
        File destf = new File(dest);
        if (destf.exists()) {
            destf.delete();
            overwrite = " [overwrite] ";
        }
        inBR = new BufferedReader(new FileReader(source));
        outT = new BufferedWriter(new FileWriter(dest));

        // start the engine
        workingC = inBR.read();
        while ((workingC >= 0) && (workingC < MORONIC_TOP_VALUE)) {

            switch (state) {

            case STATE_FRESH:
                if (workingC == Constants.CONFIG_OPEN)
                    state = STATE_FRONT;
                else
                    outT.write(workingC);
                break;

            case STATE_FRONT:
                if (workingC == Constants.CONFIG_OPEN) {
                    state = STATE_READ;
                    cBuf = new StringBuffer();
                } else {
                    state = STATE_FRESH;
                    outT.write(Constants.CONFIG_OPEN);
                    outT.write(workingC);
                }
                break;

            case STATE_READ:
                if (workingC == Constants.CONFIG_CLOSE) {
                    state = STATE_TAIL;
                } else {
                    cBuf.append((char) workingC);
                }
                break;

            case STATE_TAIL:
                if (workingC == Constants.CONFIG_CLOSE) {
                    state = STATE_FRESH;
                    theVar = cBuf.toString();

                    if (props.containsKey(theVar)) {
                        ts = (String) props.get(theVar);
                        outT.write(ts, 0, ts.length());
                    } else {
                        outT.write(Constants.CONFIG_BLANK);
                    }
                } else {
                    outT.write(Constants.CONFIG_CLOSE);
                    outT.write(workingC);
                }
                break;
            } // end case
            workingC = inBR.read();
        }
    } catch (Exception e) {
        // Might just be EOF
        //System.out.println(e);         
    } finally {
        try {
            inBR.close();
            outT.close();
            if (state != STATE_FRESH) {
                messages.append(
                        "Bad File.  Incomplete escape <<>> in file=" + source + Constants.CRUDE_SEPERATOR);
                messages.append(".........  Destination file might be corrupt.  file=" + dest
                        + Constants.CRUDE_SEPERATOR);
            }
            messages.append("Merged file to=" + dest + overwrite + Constants.CRUDE_SEPERATOR);
        } catch (Exception e) {
            messages.append("Catastrophic error merging" + source + Constants.CRUDE_SEPERATOR);
            messages.append(
                    ".........  Destination file might be corrupt.  file=" + dest + Constants.CRUDE_SEPERATOR);
        }

    }
    return messages.toString();
}

From source file:AppletFinder.java

public String readTag(BufferedReader is) {
    StringBuffer theTag = new StringBuffer("<");
    char theChar = '<';

    try {//from   w w w  .j  av  a 2  s .co m
        while (theChar != '>' && ((theChar = (char) is.read()) != -1)) {
            theTag.append(theChar);
        } // end while
    } // end try
    catch (IOException e) {
        System.err.println(e);
    }

    return theTag.toString();
}

From source file:org.openmrs.module.formentry.FormEntryUtil.java

/**
 * Convenience method to execute the given command in an environment agnostic manner
 * /*from   w w  w.ja va  2s  .  co  m*/
 * @param cmd command to execute
 * @param wd working directory (can be null)
 * @return command output
 */
private static String execCmd(String cmd, File wd) {
    log.debug("executing command: " + cmd);
    StringBuffer out = new StringBuffer();
    try {
        // Needed to add support for working directory because of a linux
        // file system permission issue.
        // Could not create lcab.tmp file in default working directory
        // (jmiranda).
        Process p = (wd != null) ? Runtime.getRuntime().exec(cmd, null, wd) : Runtime.getRuntime().exec(cmd);

        // get the stdout
        out.append("Normal cmd output:\n");
        Reader reader = new InputStreamReader(p.getInputStream());
        BufferedReader input = new BufferedReader(reader);
        int readChar = 0;
        while ((readChar = input.read()) != -1) {
            out.append((char) readChar);
        }
        input.close();
        reader.close();

        // get the errout
        out.append("ErrorStream cmd output:\n");
        reader = new InputStreamReader(p.getErrorStream());
        input = new BufferedReader(reader);
        readChar = 0;
        while ((readChar = input.read()) != -1) {
            out.append((char) readChar);
        }
        input.close();
        reader.close();

        // wait for the thread to finish and get the exit value
        int exitValue = p.waitFor();

        if (log.isDebugEnabled())
            log.debug("Process exit value: " + exitValue);

    } catch (Exception e) {
        log.error("Error while executing command: '" + cmd + "'", e);
    }

    if (log.isDebugEnabled())
        log.debug("execCmd output: \n" + out.toString());

    return out.toString();
}

From source file:com.google.gerrit.server.mail.receive.Pop3MailReceiver.java

public final int[] fetchMessage(BufferedReader reader) throws IOException {
    List<Integer> character = new ArrayList<>();
    int ch;//from w  ww .j  a  v a 2s . com
    while ((ch = reader.read()) != -1) {
        character.add(ch);
    }
    return Ints.toArray(character);
}

From source file:functionalTests.annotations.AptTest.java

private void flushOutput(BufferedReader br) {

    try {/*from   w w w. j  a  v  a  2s.  c o m*/
        if (br.read() == -1) {
            logger.debug("No output\n");
            return;
        }
        logger.debug("\n");

        for (String line = br.readLine(); line != null; line = br.readLine()) {
            logger.debug("\t|" + line + "|");
        }

        logger.debug("\n");
        logger.debug("---------------------------------------------------------------\n");
        logger.debug("\n");
    } catch (IOException e) {
        // nothing!
    }
}