Example usage for java.io BufferedReader skip

List of usage examples for java.io BufferedReader skip

Introduction

In this page you can find the example usage for java.io BufferedReader skip.

Prototype

public long skip(long n) throws IOException 

Source Link

Document

Skips characters.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    String s = "from java2s.com";

    // create and assign a new string reader
    StringReader sr = new StringReader(s);

    // create new buffered reader
    BufferedReader br = new BufferedReader(sr);

    // reads and prints BufferedReader
    int value = 0;
    while ((value = br.read()) != -1) {
        // skips a character
        br.skip(1);
        System.out.print((char) value);
    }//  ww  w. j a v  a2  s . co m

}

From source file:de.thischwa.pmcms.model.thread.LogGrabber.java

@Override
public void run() {
    BufferedReader reader = null;
    final File logFile = new File(logFileName);
    try {//from ww  w  .  j  av a2  s  .  c  o m
        reader = new BufferedReader(new FileReader(logFile));
        reader.skip(logFile.length());
    } catch (FileNotFoundException e1) {
        logger.warn("Log file not found. End file logging.");
        interrupt();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Main loop.
    while (!isInterrupted()) {
        String line;
        try {
            if (reader != null) {
                line = reader.readLine();
                while (line != null && !logAppender.getDisplay().isDisposed()) {
                    final String tmp = line;
                    logAppender.getDisplay().syncExec(new Runnable() {
                        @Override
                        public void run() {
                            logAppender.appendToLog(tmp);
                            logAppender.appendToLog("\n");
                        }
                    });
                    line = reader.readLine();
                }
            }
        } catch (IOException e1) {
            logger.error("While logging: " + e1.getMessage(), e1);
            interrupt();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.debug("Thread interrupted.");
            interrupt();
        }
    }

    IOUtils.closeQuietly(reader);
}

From source file:org.hyperic.hq.product.logparse.BaseLogParser.java

/**
 * @return If collecting IPs, this is a Hashtable
 * of "ip:url" -> RtStat summary objects.  If not collecting IPs, then
 * the keys are just the urls, without the "ip:"
 *///from w w w.  j a v a2  s.  co  m
public Hashtable parseLog(File f, String re, long len, Integer ID, int svcType, long parsedlen[],
        boolean collectIPs) throws IOException {
    GlobCompiler gc = new GlobCompiler();
    Perl5Matcher pm = new Perl5Matcher();
    Hashtable urls = new Hashtable();

    BufferedReader in = new BufferedReader(new FileReader(f));

    in.skip(len);

    String currentLine;
    this.id = ID;
    this.svcType = svcType;

    initConfig(timeMultiplier, re);

    while ((currentLine = in.readLine()) != null) {
        RtStat curr = parseLine(currentLine);

        if (curr == null) {
            continue;
        }
        if (!collectIPs)
            curr.resetIp();

        boolean logit = true;
        for (Iterator it = URLDontLog.iterator(); it.hasNext();) {
            String current = (String) it.next();
            try {
                Pattern pa = gc.compile(current);
                if (pm.matches(curr.getUrl(), pa)) {
                    logit = false;
                    break;
                }
            } catch (MalformedPatternException e) {
                this.log.error("Invalid regular expression: " + current);
                continue;
            }
        }

        /* We know that there will only be a single status in the
         * curr.status hashtable, because we have only parsed a single
         * line.  So, find that status so that we can determine if we
         * should keep this or not.
         */
        Enumeration e = curr.getStatus().keys();
        Integer stat;
        if (e.hasMoreElements()) {
            stat = (Integer) e.nextElement();
        } else {
            stat = new Integer(200);
        }

        String ipUrlKey = curr.getIpUrlKey();
        if (!StatusDontLog.contains(stat) && logit) {

            // Determine if we have already found this URL
            RtStat found = (RtStat) urls.get(ipUrlKey);

            if (found == null) {
                found = curr;
            } else {
                found.recompute(curr);

            }
            urls.put(ipUrlKey, found);
        }
    }

    in.close();

    postFileParse(f);
    parsedlen[0] = f.length();
    return urls;
}

From source file:org.openbel.framework.core.df.external.CacheableAnnotationDefinitionServiceImpl.java

/**
 * Reads the first line after the annotation header as a regular expression
 * for the annotation definition./*from   ww w .  java2s . c  om*/
 * 
 * @param annotationCacheCopy
 *            {@link File}, the annotation cache copy to parse
 * @param characterOffset
 *            <tt>long</tt>, the character offset to start reading from
 * @return {@link String} the parsed regular expression
 * @throws IOException
 *             Thrown if an IO error occurred reading the annotation file
 */
private String parseRegularExpression(File annotationCacheCopy, long characterOffset) throws IOException {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(annotationCacheCopy));
        reader.skip(characterOffset);
        return reader.readLine();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.openbel.framework.core.df.external.CacheableAnnotationDefinitionServiceImpl.java

/**
 * Reads each line after the [Values] block as enumeration values for the
 * annotation definition./* w  w w  .j  a  va2 s  .  co m*/
 * 
 * @param annotationCacheCopy {@link File}, the annotation file to read
 * from
 * @param valueDelimiter {@link String}, the delimiter that separates
 * annotation value lines
 * @param characterOffset <tt>long</tt>, the character offset of the
 * [Values] block in <tt>annotationCacheCopy</tt>
 * @return {@link List} of {@link String} that represents the enumeration
 * data
 * @throws IOException Thrown if an IO error occurred reading the BEL
 * annotation file
 */
private List<String> parseEnumData(File annotationCacheCopy, String valueDelimiter, long characterOffset)
        throws IOException {
    List<String> enumData = new ArrayList<String>();

    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(annotationCacheCopy));
        reader.skip(characterOffset);

        String line = "";
        while ((line = reader.readLine()) != null) {
            String[] lineTokens = StringUtils.splitByWholeSeparator(line, valueDelimiter);

            if (lineTokens != null && lineTokens.length >= 1) {
                enumData.add(lineTokens[0]);
            }
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
    }

    return enumData;
}

From source file:org.wso2.carbon.la.core.utils.LogPatternExtractor.java

public int processPart(long start, long end) throws IOException {
    FileInputStream fis = null;//ww w  . j a v  a 2 s. c o m
    BufferedReader reader = null;
    int count = 0;

    try {
        fis = new FileInputStream(file);
        reader = new BufferedReader(new InputStreamReader(fis));
        reader.skip(start);
        System.out.println("Reading File line by line using BufferedReader");

        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            Matcher m = apacheLogRegex.matcher(line);
            if (m.find()) {
                count++;
            }
            line = reader.readLine();
        }
        return count;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ignored) {
        }
    }
}

From source file:com.cip.crane.agent.utils.TaskHelper.java

private void writeLogToFile(BufferedReader reader, BufferedWriter writer, long fileSize, int size)
        throws IOException {
    if (fileSize > size) {
        reader.skip(fileSize - size);
    }//  w w w .  ja v  a  2s. c  o m
    String line = null;
    while ((line = reader.readLine()) != null) {
        writer.write(line + HTML_LINE_SPLITTER);
    }
}

From source file:de.ub0r.android.websms.connector.common.Utils.java

/**
 * Read {@link InputStream} and convert it into {@link String}.
 * /* w  ww .j a va  2  s  .  c om*/
 * @param is
 *            {@link InputStream} to read from
 * @param charset
 *            charset to be used to read {@link InputStream}. Can be null.
 * @param start
 *            first characters of stream that should be fetched. Set to 0,
 *            if nothing should be skipped.
 * @param end
 *            last characters of stream that should be fetched. This method
 *            might read some more characters. Set to -1 if all characters
 *            should be read.
 * @param pattern
 *            start reading at this pattern, set end = -2 to return only the
 *            line, matching this pattern
 * @return {@link String} holding all the bytes from the {@link InputStream}
 * @throws IOException
 *             IOException
 */
public static String stream2str(final InputStream is, final String charset, final int start, final int end,
        final String pattern) throws IOException {
    boolean foundPattern = false;
    if (pattern == null) {
        foundPattern = true;
    }
    InputStreamReader r;
    if (charset == null) {
        r = new InputStreamReader(is);
    } else {
        r = new InputStreamReader(is, charset);
    }
    final BufferedReader bufferedReader = new BufferedReader(r, BUFSIZE);
    final StringBuilder data = new StringBuilder();
    String line = null;
    long totalSkipped = 0;
    long skipped = 0;
    while (start > totalSkipped) {
        skipped = bufferedReader.skip(start - totalSkipped);
        if (skipped == 0) {
            break;
        }
        totalSkipped += skipped;
    }
    skipped = 0;
    while ((line = bufferedReader.readLine()) != null) {
        skipped += line.length() + 1;
        if (!foundPattern) {
            if (line.indexOf(pattern) >= 0) {
                if (end == ONLY_MATCHING_LINE) {
                    return line;
                }
                foundPattern = true;
                Log.d(TAG, "skipped: " + skipped);
            }
        }
        if (foundPattern) {
            data.append(line + "\n");

        }
        if (end >= 0 && skipped > (end - start)) {
            break;
        }
    }
    bufferedReader.close();
    if (!foundPattern) {
        return null;
    }
    return data.toString();
}

From source file:org.nuxeo.launcher.gui.logs.LogsSource.java

@Override
public void run() {
    BufferedReader in = null;
    try {/* w w  w.ja v a  2s  .  c om*/
        while (!logFile.exists()) {
            Thread.sleep(WAIT_FOR_FILE_EXISTS);
        }
        in = new BufferedReader(new FileReader(logFile));
        // Avoid reading and formating chars which won't be displayed
        if (charsToSkip > 0) {
            in.skip(charsToSkip);
        }
        // marker for detecting log rotate
        long lastModified = logFile.lastModified();
        while (true) {
            if (pause) {
                synchronized (this) {
                    wait();
                }
            }
            String line = in.readLine();
            if (line != null) {
                lastModified = logFile.lastModified();
                setChanged();
                notifyObservers(line);
            } else {
                if (logFile.lastModified() > lastModified) {
                    log.debug("File rotation detected");
                    IOUtils.closeQuietly(in);
                    in = new BufferedReader(new FileReader(logFile));
                } else {
                    synchronized (this) {
                        wait(WAIT_FOR_READING_CONTENT);
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        log.debug(e);
    } catch (IOException e) {
        log.error(e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.rhq.core.pluginapi.util.ResponseTimeLogParser.java

/**
 * Parse the log file, starting at the offset corresponding to the file's size after the last time this method was
 * called. Immediately after parsing, the file will be truncated, permissions permitting. If the log file does not
 * exist, a warning will be logged and the method will return. The parsed response-time data will be added to the
 * passed-in CallTimeData object./*from w  w w  . ja v a  2s  .co  m*/
 *
 * @param callTimeData the parsed response-time data will be added to this object
 * @throws IOException if an error occurs reading the log file
 */
public synchronized void parseLog(CallTimeData callTimeData) throws IOException {
    log.debug("Parsing response-time log file " + this.logFile + "...");
    BufferedReader in = null;

    try {
        in = new BufferedReader(new FileReader(this.logFile));

        in.skip(this.startingOffset);

        String currentLine;
        while ((currentLine = in.readLine()) != null) {
            LogEntry logEntry;
            try {
                logEntry = parseLine(currentLine);
            } catch (Exception e) {
                log.debug("Problem parsing line [" + currentLine + "] - cause: " + e);
                continue;
            }

            String url = logEntry.getUrl();

            // The URL should always begin with a slash. If it doesn't, log an error and skip the entry,
            // so we don't end up with bogus data in the DB.
            if (url.charAt(0) != '/') {
                String truncatedUrl = url.substring(0, Math.min(url.length(), 120));
                if (url.length() > 120)
                    truncatedUrl += "...";
                log.error("URL ('" + truncatedUrl
                        + "') parsed from response-time log file does not begin with '/'. "
                        + "Line being parsed is [" + currentLine + "].");
                continue;
            }

            if (isExcluded(url)) {
                continue;
            }

            // Only collect stats for successful (2xx or 3xx) requests...
            if ((logEntry.getStatusCode() != null)
                    && ((logEntry.getStatusCode() < 200) || (logEntry.getStatusCode() >= 400))) {
                continue;
            }

            String transformedUrl = applyTransforms(url);
            try {
                callTimeData.addCallData(transformedUrl, new Date(logEntry.getStartTime()),
                        logEntry.getDuration());
            } catch (IllegalArgumentException iae) {
                // if any issue with the data, log them and continue processing the rest of the report
                log.error(iae);
            }
        }
    } catch (FileNotFoundException e) {
        log.warn("Response-time log file '" + this.logFile + "' does not exist.");
        return;
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (Exception e) {
                log.error("Unable to close response-time log file.", e);
            }
        }
    }

    /*
     * After we're done parsing the file, truncate it. This is kosher, assuming we own any file being parsed by this
     * parser.
     */
    truncateLog(this.logFile);
    this.startingOffset = this.logFile.length();
}