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:itdelatrisu.opsu.Utils.java

/**
 * Returns a the contents of a URL as a string.
 * @param url the remote URL//from  w w  w .  ja v  a2 s.com
 * @return the contents as a string, or null if any error occurred
 * @author Roland Illig (http://stackoverflow.com/a/4308662)
 * @throws IOException if an I/O exception occurs
 */
public static String readDataFromUrl(URL url) throws IOException {
    // open connection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(Download.CONNECTION_TIMEOUT);
    conn.setReadTimeout(Download.READ_TIMEOUT);
    conn.setUseCaches(false);
    try {
        conn.connect();
    } catch (SocketTimeoutException e) {
        Log.warn("Connection to server timed out.", e);
        throw e;
    }

    if (Thread.interrupted())
        return null;

    // read contents
    try (InputStream in = conn.getInputStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = rd.read()) != -1)
            sb.append((char) c);
        return sb.toString();
    } catch (SocketTimeoutException e) {
        Log.warn("Connection to server timed out.", e);
        throw e;
    }
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*from ww  w .j av a  2 s. c  om*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:jshm.sh.scraper.wiki.ActionsScraper.java

public static Map<String, List<Action>> scrape(final Reader reader, final Map<String, List<Action>> ret)
        throws IOException, ScraperException {
    if (null == ret)
        throw new NullPointerException("ret");

    BufferedReader in = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);

    StringBuilder sb = null;/*from w ww.j  av  a2s.  c  o m*/
    String lastKey = null;
    Action action = null;

    int c = -1, leftBraceCount = 0, rightBraceCount = 0;
    boolean isQuotedString = false;
    Expect expect = Expect.LEFT_BRACE;

    while (-1 != (c = in.read())) {
        switch (expect) {
        case LEFT_BRACE:
            if ('{' == c) {
                leftBraceCount++;

                if (2 == leftBraceCount) {
                    LOG.finer("got 2 left braces, expecting name");
                    expect = Expect.NAME;
                    action = new Action();
                    sb = new StringBuilder();
                    isQuotedString = false;
                }
            }

            // skipping non action block
            continue;

        case NAME:
            if (Character.isLetter(c)) {
                sb.append((char) c);
                continue;
            } else if ('}' == c) {
                // no key/value pairs
                rightBraceCount++;
                action.name = sb.toString();
                if (null == ret.get(action.name))
                    ret.put(action.name, new ArrayList<Action>());
                ret.get(action.name).add(action);
                expect = Expect.RIGHT_BRACE;

                LOG.finer("got right brace after name (" + action.name + "), action has no args");
                continue;
            } else if (Character.isWhitespace(c)) {
                // we've read some characters for the name
                if (0 != sb.length()) {
                    action.name = sb.toString();
                    if (null == ret.get(action.name))
                        ret.put(action.name, new ArrayList<Action>());
                    ret.get(action.name).add(action);
                    expect = Expect.KEY;
                    sb = new StringBuilder();
                    isQuotedString = false;

                    LOG.finer("got whitespace after name (" + action.name + ")");
                }

                // else there's whitespace before the name

                continue;
            }

            throw new ScraperException("expecting next letter in name or whitespace after, got: " + (char) c);

        case KEY:
            if (Character.isLetter(c)) {
                sb.append((char) c);
                continue;
            } else if (Character.isWhitespace(c) && 0 == sb.length()) {
                // extra whitespace between last thing and this key 
                continue;
            } else if ('}' == c) {
                if (0 != sb.length())
                    throw new ScraperException("expecting next letter in key but got right brace");

                LOG.finer("got right brace after last value");

                rightBraceCount++;
                expect = Expect.RIGHT_BRACE;
                continue;
            } else if ('=' == c) {
                lastKey = sb.toString();

                LOG.finer("got equals sign after key (" + lastKey + ")");

                expect = Expect.VALUE;
                sb = new StringBuilder();
                isQuotedString = false;
                continue;
            }

            throw new ScraperException("expecting next letter in key or equals sign, got: " + (char) c);

        case VALUE:
            if (isQuotedString && '"' != c && '}' != c) {
                sb.append((char) c);
                continue;
            } else if ('"' == c || (isQuotedString && '}' == c)) {
                if ('}' == c) {
                    // malformed, no end quote
                    isQuotedString = false;
                } else {
                    isQuotedString = !isQuotedString;
                }

                if (isQuotedString) {
                    LOG.finest("got opening quote for value of key (" + lastKey + ")");
                } else {
                    String value = org.htmlparser.util.Translate.decode(sb.toString().trim());

                    LOG.finer("got closing quote for value (" + value + ")");

                    action.args.put(lastKey, value);

                    if ('}' == c) {
                        expect = Expect.RIGHT_BRACE;
                        rightBraceCount++;
                    } else {
                        expect = Expect.KEY;
                    }

                    lastKey = null;
                    sb = new StringBuilder();
                    isQuotedString = false;
                }

                continue;
            } else if (Character.isWhitespace(c)) {
                LOG.finer("got whitespace before value for key (" + lastKey + ")");
                expect = Expect.KEY;
                lastKey = null;
                sb = new StringBuilder();
                isQuotedString = false;

                continue;
            }

            throw new ScraperException("expecting quote or next letter in value, got: " + (char) c);

        case RIGHT_BRACE:
            if ('}' == c) {
                rightBraceCount++;

                if (2 == rightBraceCount) {
                    LOG.finer("got 2nd right brace");
                    leftBraceCount = rightBraceCount = 0;
                    expect = Expect.LEFT_BRACE;
                    continue;
                }
            }

            throw new ScraperException("expecting 2nd right brace, got " + (char) c);
        }
    }

    return ret;
}

From source file:org.eclipse.smila.utils.file.EncodingHelper.java

/**
 * Checks if the given bytes array represents some kind of markup language (xml, html), by checking if the first non
 * whitespace character is a <. Does not allow a BOM at the start of the bytes.
 *
 * @param bytes/*from   w  ww  .  j av a2s . co m*/
 *          the byte[] to check for markup content
 * @return true if the bytes contain xml or html markup, false otherwise
 * @throws IOException
 *           if any error occurs
 */
public static boolean isMarkup(final byte[] bytes) throws IOException {
    if (bytes != null) {
        BufferedReader inputReader = null;
        try {
            // find first non whitespace character
            // markup should begin with a <
            inputReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
            int buff = inputReader.read();
            while (buff != -1) {
                switch (buff) {
                case 0:
                    break;
                case ' ':
                    break;
                case '\r':
                    break;
                case '\n':
                    break;
                case '\t':
                    break;
                case '<':
                    return true;
                default:
                    return false;
                }
                buff = inputReader.read();
            } // while
        } finally {
            IOUtils.closeQuietly(inputReader);
        }
    }
    return false;
}

From source file:com.iksgmbh.sql.pojomemodb.utils.FileUtil.java

/**
 * Uses reader and writer to perform copy
 * @param sourcefile/* ww w .j a v  a  2  s  . com*/
 * @param targetFile
 */
public static void copyTextFile(final File sourcefile, final File targetFile) {
    if (!sourcefile.exists()) {
        throw new RuntimeException("Sourcefile does not exist: " + sourcefile.getAbsolutePath());
    }
    if (!sourcefile.isFile()) {
        throw new RuntimeException("Sourcefile is no file: " + sourcefile.getAbsolutePath());
    }
    final String targetdir = targetFile.getParent();
    if (!targetFile.getParentFile().exists()) {
        throw new RuntimeException("TargetDirectory does not exist: " + targetdir);
    }

    BufferedReader in = null;
    BufferedWriter out = null;
    try {
        out = IOEncodingHelper.STANDARD.getBufferedWriter(targetFile);
        in = IOEncodingHelper.STANDARD.getBufferedReader(sourcefile);
        int c;

        while ((c = in.read()) != -1)
            out.write(c);
    } catch (Exception e) {
        throw new RuntimeException("Error copying " + sourcefile.getAbsolutePath() + " to " + targetdir, e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException("Error closing reader " + in, e);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException("Error writer reader " + out, e);
            }
        }
    }
}

From source file:org.blazr.extrastorage.ExtraStorage.java

private static String getText(String myURL, boolean main_thread) {
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;//from   w  w w.j  av  a2  s. c  o m
    try {
        URL url = new URL(StringEscapeUtils.escapeHtml(myURL));
        urlConn = url.openConnection();
        if (urlConn != null)
            if (main_thread)
                urlConn.setReadTimeout(5 * 1000);
            else
                urlConn.setReadTimeout(30 * 1000);
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (IOException e) {
        if (e.getMessage().contains("429"))
            return "wait";
        return null;
    } catch (Exception e) {
        return null;
    }
    return sb.toString();
}

From source file:org.apache.any23.mime.TikaMIMETypeDetector.java

/**
 * Extracts a sample data from the input stream, from the current
 * mark to the first <i>breakChar</i> char.
 *
 * @param is the input stream to sample.
 * @param breakChar the char to break to sample.
 * @return the sample string.//ww w .  j  a v a 2  s. co  m
 * @throws IOException if an error occurs during sampling.
 */
private static StringBuilder extractDataSample(InputStream is, char breakChar, char[] insideBlockCharacters,
        char[] lineCommentChars, char[] outsideBlockCharacters, char[] switchBlockCharacters)
        throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    // TODO: Make this configurable
    final int MAX_SIZE = 1024 * 2;
    int c;
    boolean insideBlock = false;
    int read = 0;
    br.mark(MAX_SIZE);
    try {
        while ((c = br.read()) != -1) {
            read++;
            if (sb.length() > MAX_SIZE) {
                break;
            }

            if (!insideBlock) {
                for (char nextLineCommentChar : lineCommentChars) {
                    // if we hit a comment character that signals the rest of the line is a comment 
                    // then we do not want to extract any of the rest of the line, including the 
                    // comment character for our sample, so we read to the end of the line and then 
                    // continue the loop without appending anything
                    if (c == nextLineCommentChar) {
                        br.readLine();
                        continue;
                    }
                }
            }

            for (char nextInsideChar : insideBlockCharacters) {
                if (c == nextInsideChar)
                    insideBlock = true;
            }

            for (char nextOutsideChar : outsideBlockCharacters) {
                if (c == nextOutsideChar)
                    insideBlock = false;
            }

            for (char nextSwitchChar : switchBlockCharacters) {
                if (c == nextSwitchChar)
                    insideBlock = !insideBlock;
            }
            sb.append((char) c);
            if (!insideBlock && breakChar == c) {
                break;
            }
        }
    } finally {
        is.reset();
        br.reset();
    }
    return sb;
}

From source file:com.microsoft.tfs.util.NewlineUtils.java

/**
 * Detects which newline convention used given {@link Reader}. The first
 * newline sequence detected is returned (<code>null</code> if none is
 * detected)./*w w  w . j a  v a 2  s. c om*/
 *
 * The return value is a string containing one of the fields in this class,
 * or for Windows-style newlines, a string with a {@link #CARRIAGE_RETURN}
 * followed by {@link #LINE_FEED}.
 *
 * @param reader
 *        the {@link Reader} to read from
 * @return the newline sequence detected, <code>null</code> if the reader
 *         was <code>null</code> or no newline sequence was detected
 */
public static String detectNewlineConvention(final Reader reader) {
    if (reader != null) {
        final BufferedReader bufferedReader = new BufferedReader(reader);

        int currentCharacter;
        try {
            while ((currentCharacter = bufferedReader.read()) != -1) {
                /*
                 * Move the index past the second character of the Windows
                 * newline sequence (CRLF), if applicable.
                 */
                if (currentCharacter == CARRIAGE_RETURN) {
                    if (bufferedReader.read() == LINE_FEED) {
                        /*
                         * Found a Windows-style CRLF.
                         */
                        return "" + (CARRIAGE_RETURN) + (LINE_FEED); //$NON-NLS-1$
                    }
                }

                /*
                 * All other newline sequences are single characters.
                 */
                if (isNewlineCharacter((char) currentCharacter)) {
                    return "" + ((char) currentCharacter); //$NON-NLS-1$
                }
            }
        } catch (final IOException e) {
            log.error("Error detecting newline convention", e); //$NON-NLS-1$
        }
    }

    log.debug("Could not detect any newlines in stream"); //$NON-NLS-1$

    return null;
}

From source file:com.microsoft.tfs.util.NewlineUtils.java

/**
 * <p>//  www .  j  a va  2 s  .  c om
 * Replaces newlines read from the given {@link Reader} with the
 * <code>replacement</code> argument and writes the results to the given
 * {@link Writer}.
 * </p>
 * <p>
 * This method internally wraps the given reader in a {@link BufferedReader}
 * (so it can mark and rewind the stream to read multi-character EOL
 * sequences), so the caller may omit its own buffering layer. The
 * {@link Writer} is not automatically buffered.
 * </p>
 *
 * @see #replaceNewlines(String, String, boolean)
 *
 * @param reader
 *        The input {@link Reader} to read characters from. If the input is
 *        <code>null</code>, the method returns immediately (no characters
 *        are written to the {@link Writer}).
 * @param writer
 *        The output {@link Writer} where characters and converted newlines
 *        are written (must not be <code>null</code>)
 * @param replacement
 *        The replacement <code>String</code> for newlines (must not be
 *        <code>null</code>)
 * @param groupNewlines
 *        controls the behavior of this method when there are consecutive
 *        newlines in the input (see the Javadoc for the method that takes
 *        String input for details)
 * @throws IOException
 *         if an error occurred reading from the {@link Reader}, writing to
 *         the {@link Writer}. These errors may include the discovery of
 *         invalid character sequences in the input.
 */
public static void replaceNewlines(final Reader reader, final Writer writer, final String replacement,
        final boolean groupNewlines) throws IOException {
    if (reader == null) {
        return;
    }

    Check.notNull(writer, "output"); //$NON-NLS-1$
    Check.notNull(replacement, "replacement"); //$NON-NLS-1$

    final BufferedReader bufferedReader = new BufferedReader(reader);

    boolean inNewlineGroup = false;

    int currentCharacter;
    while ((currentCharacter = bufferedReader.read()) != -1) {
        final boolean isNewlineCharacter = isNewlineCharacter((char) currentCharacter);

        /*
         * Move the index past the second character of the Windows newline
         * sequence (CRLF), if applicable.
         */
        if (currentCharacter == CARRIAGE_RETURN) {
            /*
             * Set a mark so we can rewind after peeking.
             */
            bufferedReader.mark(BUFFERED_READER_MARK_READ_AHEAD_CHARACTERS);

            final int nextCharacter = bufferedReader.read();

            if (nextCharacter == LINE_FEED) {
                /*
                 * Is a line feed, set this as the current character for
                 * evaluation this iteration.
                 */
                currentCharacter = nextCharacter;
            } else {
                /*
                 * Not a line feed or end of stream.
                 */
                bufferedReader.reset();
            }
        }

        if (isNewlineCharacter) {
            if (groupNewlines) {
                /*
                 * Just record that we've entered a newline group - we'll
                 * apply the replacement string to the result after we've
                 * exited the group.
                 */
                inNewlineGroup = true;
            } else {
                /*
                 * Not in grouping mode - each distinct newline character
                 * gets its own replacement.
                 */
                writer.write(replacement);
            }
        } else {
            if (groupNewlines && inNewlineGroup) {
                /*
                 * Exiting a newline group - apply the replacement to the
                 * result.
                 */
                writer.write(replacement);
                inNewlineGroup = false;
            }
            writer.write(currentCharacter);
        }
    }

    if (inNewlineGroup) {
        /*
         * The input string terminated while we were in a newline group, so
         * be sure to add in the replacement character for this group
         * (without this check, newline groups at the end of strings would
         * be ignored).
         */
        writer.write(replacement);
        inNewlineGroup = false;
    }
}

From source file:jeplus.INSELWinTools.java

/**
 * Call INSEL executable file to run the simulation
 * @param config INSEL Configuration/*from   www .j a  va  2s .  c  o m*/
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param useReadVars Whether or not to use readvars after simulation
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runINSEL(INSELConfig config, String WorkDir, String modelfile) {

    int ExitValue = -99;

    try {
        // Trace simulation time
        Date start = new Date();

        // Run EnergyPlus executable
        String CmdLine = config.getResolvedInselEXEC() + " " + modelfile;
        Process EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(WorkDir));

        BufferedReader ins = new BufferedReader(new InputStreamReader(EPProc.getInputStream()));
        // Use console output as the report file
        BufferedWriter outs = new BufferedWriter(new FileWriter(WorkDir + config.ScreenFile, false));
        outs.newLine();
        outs.write("Calling insel.exe - " + (new SimpleDateFormat()).format(start));
        outs.newLine();
        outs.write("Command line: " + WorkDir + ">" + CmdLine);
        outs.newLine();

        int res = ins.read();
        while (res != -1) {
            outs.write(res);
            res = ins.read();
        }
        ins.close();
        outs.newLine();
        outs.write("Simulation time: " + Long.toString((new Date().getTime() - start.getTime()) / 1000)
                + " seconds");
        outs.flush();
        outs.close();

        EPProc.waitFor();
        ExitValue = EPProc.exitValue();
    } catch (IOException | InterruptedException e) {
        logger.error("Exception during INSEL execution.", e);
    }

    // Return Radiance exit value
    return ExitValue;
}