Example usage for java.io RandomAccessFile readLine

List of usage examples for java.io RandomAccessFile readLine

Introduction

In this page you can find the example usage for java.io RandomAccessFile readLine.

Prototype


public final String readLine() throws IOException 

Source Link

Document

Reads the next line of text from this file.

Usage

From source file:org.ala.spatial.util.AnalysisJobMaxent.java

private String getMaxentError(File file, int count) {
    try {//from  www .  jav a 2  s  .co  m
        RandomAccessFile rf = new RandomAccessFile(file, "r");

        // first check if maxent threw a 'No species selected' error
        String nosp = rf.readLine(); // first line: date/time
        nosp = rf.readLine(); // second line: maxent version
        nosp = rf.readLine(); // third line: "No species selected"
        if (nosp.equals("No species selected")) {
            return "No species selected";
        }

        long flen = file.length() - 1;
        int nlcnt = -1;
        StringBuilder lines = new StringBuilder();
        while (nlcnt != count) {
            rf.seek(flen--);
            char c = (char) rf.read();
            lines.append(c);
            if (c == '\n') {
                nlcnt++;
            }

        }
        String line = lines.reverse().toString();
        if (line.contains("Warning: Skipping species because it has 0 test samples")) {
            return "Warning: Skipping species because it has 0 test samples";
        }

        rf.close();
    } catch (Exception e) {
        System.out.println("Unable to read lines");
        e.printStackTrace(System.out);
    }

    // return false anyways
    return null;
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void dumpSequentialRA() throws Exception {
    RandomAccessFile ra = new RandomAccessFile(logfile, "r");
    for (int i = 0; i < LINES; i++) {
        ra.readLine();
    }//from   ww  w. j a va2s.c  o  m
    Profiler profiler = new Profiler();
    profiler.setExpectedTotal(SEQUENTIAL_RUNS);
    for (int i = 0; i < SEQUENTIAL_RUNS; i++) {
        ra.seek(0);
        for (int j = 0; j < LINES; j++) {
            ra.readLine();
        }
        profiler.beat();
    }
    System.out.println("Performed " + SEQUENTIAL_RUNS + " full RA reads at "
            + Math.round(profiler.getBps(false)) + " reads/second");
}

From source file:raptor.service.DictionaryService.java

public String[] getWordsThatStartWith(String string) {
    List<String> result = new ArrayList<String>(10);

    string = string.toLowerCase();/* w w w.  ja  v  a 2 s  .  c  o m*/
    long startTime = System.currentTimeMillis();
    RandomAccessFile raf = null;
    try {
        File file = new File(DICTIONARY_PATH);
        raf = new RandomAccessFile(file, "r");

        long low = 0;
        long high = file.length();

        long p = -1;
        while (low < high) {
            long mid = (low + high) / 2;
            p = mid;
            while (p >= 0) {
                raf.seek(p);

                char c = (char) raf.readByte();
                if (c == '\n')
                    break;
                p--;
            }
            if (p < 0)
                raf.seek(0);
            String line = raf.readLine();
            // Useful for debugging
            // System.out.println("-- " + mid + " " + line);
            if (line == null) {
                low = high;
            } else {
                int compare = line.compareTo(string);
                if (compare < 0) {
                    low = mid + 1;
                } else if (compare == 0) {
                    low = p;
                    break;
                } else {
                    high = mid;
                }
            }
        }

        p = low;
        while (p >= 0 && p < high) {
            raf.seek(p);
            if (((char) raf.readByte()) == '\n')
                break;
            p--;
        }

        if (p < 0)
            raf.seek(0);

        String line = raf.readLine();
        while (line != null && line.startsWith(string)) {
            result.add(line);
            line = raf.readLine();
        }
    } catch (Throwable t) {
        Raptor.getInstance().onError("Error reading dictionary file: " + DICTIONARY_PATH, t);
    } finally {
        try {
            raf.close();
        } catch (Throwable t) {
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Searched " + string + " (" + (System.currentTimeMillis() - startTime) + ") " + result);
        }

    }
    return result.toArray(new String[0]);
}

From source file:org.slc.sli.sample.transform.CcsCsvReader.java

private String tail(File file) {
    try {/*  w w w  . ja  v a 2 s .  co m*/
        RandomAccessFile fileHandler = new RandomAccessFile(file, "r");
        long fileLength = file.length() - 1;
        long filePointer;

        for (filePointer = fileLength; filePointer != -1; filePointer--) {
            fileHandler.seek(filePointer);
            int readByte = fileHandler.readByte();

            if (readByte == 0xA) {
                if (filePointer == fileLength) {
                    continue;
                } else {
                    break;
                }
            } else if (readByte == 0xD) {
                if (filePointer == fileLength - 1) {
                    continue;
                } else {
                    break;
                }
            }

        }

        String lastLine = fileHandler.readLine();
        fileHandler.close();

        return lastLine.substring(1);
    } catch (java.io.FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (java.io.IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:it.drwolf.ridire.session.async.JobDBDataUpdater.java

private String getJobStatus(String encodedJobName) throws HttpException, IOException, DocumentException {
    // back compatibility Heritrix 2
    if (encodedJobName.startsWith("completed-")) {
        return CrawlStatus.FINISHED.toString();
    }/*w  ww  .j  av a 2 s. c o m*/
    File jobDir = new File(this.jobsDir + CrawlerManager.FILE_SEPARATOR + encodedJobName);
    String[] files = jobDir.list();
    if (files == null || files.length < 2) {
        return CrawlStatus.CREATED.toString();
    }
    String ret = CrawlStatus.CREATED.toString();
    RandomAccessFile progressStatistics = null;
    Calendar now = new GregorianCalendar();
    Date comparingDate = DateUtils.addDays(now.getTime(), -3);
    try {
        progressStatistics = new RandomAccessFile(
                this.jobsDir + CrawlerManager.FILE_SEPARATOR + encodedJobName + CrawlerManager.FILE_SEPARATOR
                        + "logs" + CrawlerManager.FILE_SEPARATOR + "progress-statistics.log",
                "r");
        if (progressStatistics != null) {
            progressStatistics.seek(Math.max(0, progressStatistics.length() - 3000));
            String line = progressStatistics.readLine();
            StringBuffer buffer = new StringBuffer();
            while (line != null) {
                buffer.append(line + "\n");
                line = progressStatistics.readLine();
            }
            String progressStatisticsContent = buffer.toString();
            Matcher m = this.progressStatisticsDatePattern.matcher(progressStatisticsContent);
            int start = 0;
            String lastDateString = "";
            while (m.find(start)) {
                start = m.end();
                lastDateString = m.group();
            }
            Date lastDate = this.progressStatisticsDateFormat.parse(lastDateString);
            if (!progressStatisticsContent.contains("CRAWL ENDED - Finished")
                    && lastDate.after(comparingDate)) {
                ret = CrawlStatus.RUNNING.toString();
            } else {
                ret = CrawlStatus.FINISHED.toString();
            }

        }
    } catch (FileNotFoundException e) {
        // TODO: handle exception
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (progressStatistics != null) {
            progressStatistics.close();
        }
    }
    // File crawlReport = new File(this.jobsDir + FILE_SEPARATOR
    // + encodedJobName + FILE_SEPARATOR + "reports" + FILE_SEPARATOR
    // + "crawl-report.txt");
    // if (crawlReport != null && crawlReport.canRead()) {
    // String crawlReportContent = FileUtils.readFileToString(crawlReport);
    // if (crawlReportContent.contains("crawl status: Finished")) {
    // ret = CrawlStatus.FINISHED.toString();
    // }
    // }
    return ret;
}

From source file:raptor.service.DictionaryService.java

/**
 * This method started out as code from/*w  w  w  . j  av  a2 s  .c  o  m*/
 * http://stackoverflow.com/questions/736556/binary
 * -search-in-a-sorted-memory-mapped-file-in-java
 * 
 * It has been altered to fix some bugs.
 */
protected boolean binarySearch(String filename, String string) {
    string = string.toLowerCase();
    long startTime = System.currentTimeMillis();
    RandomAccessFile raf = null;
    boolean result = false;
    try {
        File file = new File(filename);
        raf = new RandomAccessFile(file, "r");

        long low = 0;
        long high = file.length();

        long p = -1;
        while (low < high) {
            long mid = (low + high) / 2;
            p = mid;
            while (p >= 0) {
                raf.seek(p);

                char c = (char) raf.readByte();
                if (c == '\n')
                    break;
                p--;
            }
            if (p < 0)
                raf.seek(0);
            String line = raf.readLine();
            // Useful for debugging
            // System.out.println("-- " + mid + " " + line);
            if (line == null) {
                low = high;
            } else {
                int compare = line.compareTo(string);
                if (compare < 0) {
                    low = mid + 1;
                } else if (compare == 0) {
                    return true;
                } else {
                    high = mid;
                }
            }
        }

        p = low;
        while (p >= 0 && p < high) {
            raf.seek(p);
            if (((char) raf.readByte()) == '\n')
                break;
            p--;
        }

        if (p < 0)
            raf.seek(0);

        while (true) {
            String line = raf.readLine();
            // Useful for debugging.
            // System.out.println("searching forwards " + line);
            if (line == null) {
                result = false;
                break;
            } else if (line.equals(string)) {
                result = true;
                break;
            } else if (!line.startsWith(string)) {
                result = false;
                break;
            }
        }
    } catch (Throwable t) {
        Raptor.getInstance().onError("Error reading dictionary file: " + DICTIONARY_PATH, t);
    } finally {
        try {
            raf.close();
        } catch (Throwable t) {
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Searched " + string + " (" + (System.currentTimeMillis() - startTime) + ") " + result);
        }

    }
    return result;
}

From source file:com.stimulus.archiva.domain.Volume.java

protected void readVolumeInfoLines(RandomAccessFile randomAccessFile) {
    logger.debug("readVolumeInfoLines()");
    String line;/*w  w  w . j  a  v a 2 s  .  c o  m*/
    StringTokenizer st;
    try {
        randomAccessFile.seek(0);
        while ((line = randomAccessFile.readLine()) != null) {

            if (line.startsWith("#") || line.length() < 1)
                continue;
            try {
                st = new StringTokenizer(line, ":");
            } catch (NoSuchElementException nse) {
                logger.debug("possible volumeinfo corruption. no such element.");
                continue;
            }
            String name = st.nextToken();
            if (name.toLowerCase(Locale.ENGLISH).trim().equals("modified"))
                setClosedDate(DateUtil.convertStringToDate(st.nextToken().trim()));
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("latestarchived"))
                setClosedDate(DateUtil.convertStringToDate(st.nextToken().trim()));
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("closed"))
                setClosedDate(DateUtil.convertStringToDate(st.nextToken().trim()));
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("created"))
                setCreatedDate(DateUtil.convertStringToDate(st.nextToken().trim()));
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("earliestarchived"))
                setCreatedDate(DateUtil.convertStringToDate(st.nextToken().trim()));
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("version"))
                setVersion(st.nextToken().trim());
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("id"))
                setID(st.nextToken().trim());
            else if (name.toLowerCase(Locale.ENGLISH).trim().equals("status")) {
                Status status = Status.CLOSED; // default
                try {
                    status = Status.valueOf(st.nextToken().trim());
                } catch (IllegalArgumentException iae) {
                    logger.error(
                            "failed to load volume.info: status attribute is set to an illegal value {vol='"
                                    + toString() + "'}");
                    logger.error("volume will be set closed (due to error)");
                }

                setStatusNoAssertions(status);
            }
            ;

        }
        // we make sure that NEW entries become UNUSED
        if (getStatus() == Volume.Status.NEW)
            setStatus(Volume.Status.UNUSED);
        // make sure that volume closed date is not set, when volume is active
        if (getStatus() == Volume.Status.ACTIVE && getClosedDate() != null) {
            setClosedDate(null);
        }

    } catch (Exception e) {
        logger.debug("failed to read volumeinfo {" + toString() + "}", e);
    }

}

From source file:org.opencb.cellbase.lib.db.VariantAnnotationCalculatorTest.java

private void skipVepFileHeader(RandomAccessFile raf) throws IOException {
    String line;//w ww  .j a v a2s. com
    long pos;
    do {
        pos = raf.getFilePointer();
        line = raf.readLine();
    } while (line.startsWith("#"));
    raf.seek(pos);
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void dumpSpeedRA() throws Exception {
    Random random = new Random();
    RandomAccessFile ra = new RandomAccessFile(logfile, "r");
    long[] pos = getPositions();
    // Warming up
    for (int i = 0; i < 1000; i++) {
        ra.seek(pos[random.nextInt(LINES)]);
        ra.readLine();
    }//  ww w  .  j a v  a2  s  .  c om
    Profiler profiler = new Profiler();
    profiler.setExpectedTotal(SPEED_SEEKS);
    for (int i = 0; i < SPEED_SEEKS; i++) {
        ra.seek(pos[random.nextInt(LINES)]);
        ra.readLine();
        profiler.beat();
    }
    System.out.println("Performed " + SPEED_SEEKS + " RA seeks & " + "reads at "
            + Math.round(profiler.getBps(false)) + " seeks/second");
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void testVsRandomAccess() throws Exception {
    RandomAccessFile ra = new RandomAccessFile(logfile, "r");
    LineReader lr = new LineReader(logfile, "r");
    int count = 0;
    while (count++ < LINES) {
        assertEquals("The lr line should match ra line", ++count + "'" + fixISO(ra.readLine()) + "'",
                count + "'" + lr.readLine() + "'");
    }/*from   ww  w .ja v  a 2 s  .  c  o m*/
}