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:Main.java

public static float getTotalRAM() {
    RandomAccessFile reader = null;
    String load = null;//from   www .  j av a  2  s.  c o m
    DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
    double totRam = 0;
    float lastValue = 0;
    try {
        reader = new RandomAccessFile("/proc/meminfo", "r");
        load = reader.readLine();

        // Get the Number value from the string
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m = p.matcher(load);
        String value = "";
        while (m.find()) {
            value = m.group(1);
            // System.out.println("Ram : " + value);
        }
        reader.close();

        totRam = Double.parseDouble(value);
        // totRam = totRam / 1024;

        float mb = (float) (totRam / 1024.0f);
        float gb = (float) (totRam / 1048576.0f);
        float tb = (float) (totRam / 1073741824.0f);

        lastValue = gb;
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        // Streams.close(reader);
    }

    return lastValue;
}

From source file:org.mycontroller.standalone.api.jaxrs.utils.McServerLogFile.java

public static LogFileJson getLogUpdate(Long lastKnownPosition, Long lastNPosition) {
    if (lastNPosition != null && appLogFile.length() > lastNPosition) {
        lastKnownPosition = appLogFile.length() - lastNPosition;
    } else if (lastKnownPosition != null && appLogFile.length() <= lastKnownPosition) {
        return LogFileJson.builder().lastKnownPosition(lastKnownPosition).build();
    }/*  ww w.ja  v a  2  s. c om*/
    if (lastKnownPosition == null) {
        lastKnownPosition = 0l;
    }

    //Set maximum limit
    if ((appLogFile.length() - lastKnownPosition) > MAX_POSITION_LIMIT) {
        lastKnownPosition = appLogFile.length() - MAX_POSITION_LIMIT;
    }

    logBuilder.setLength(0);
    // Reading and writing file
    RandomAccessFile readFileAccess = null;
    try {
        readFileAccess = new RandomAccessFile(appLogFile, "r");
        readFileAccess.seek(lastKnownPosition);
        String log = null;
        while ((log = readFileAccess.readLine()) != null) {
            logBuilder.append(log).append("\n");
        }
        lastKnownPosition = readFileAccess.getFilePointer();
    } catch (FileNotFoundException ex) {
        _logger.error("Error,", ex);
    } catch (IOException ex) {
        _logger.error("Error,", ex);
    } finally {
        if (readFileAccess != null) {
            try {
                readFileAccess.close();
            } catch (IOException ex) {
                _logger.error("Error,", ex);
            }
        }
    }
    return LogFileJson.builder().lastKnownPosition(lastKnownPosition).data(logBuilder.toString()).build();
}

From source file:org.wso2.carbon.integration.framework.utils.CodeCoverageUtils.java

private static void instrumentSelectedFiles(String carbonHome) throws Exception {
    File instrumentationTxt = System.getProperty("instr.file") != null
            ? new File(System.getProperty("instr.file"))
            : new File(System.getProperty("basedir") + File.separator + "src" + File.separator + "test"
                    + File.separator + "resources" + File.separator + "instrumentation.txt");
    List<String> filePatterns = new ArrayList<String>();
    if (instrumentationTxt.exists()) {
        RandomAccessFile rf = new RandomAccessFile(instrumentationTxt, "r");
        try {//from w ww  . jav a 2  s  .co m
            String line;
            while ((line = rf.readLine()) != null) {
                filePatterns.add(line);
            }
        } finally {
            rf.close();
        }
    }

    // Instrument the bundles which match the speficied patterns in <code>filePatterns</code>
    File plugins = new File(carbonHome + File.separator + "repository" + File.separator + "components"
            + File.separator + "plugins");
    int instrumentedFileCount = 0;
    for (File file : plugins.listFiles()) {
        if (file.isFile()) {
            if (filePatterns.isEmpty()) { // If file patterns are not specified, instrument all files
                instrument(file);
                instrumentedFileCount++;
            } else {
                for (String filePattern : filePatterns) {
                    if (file.getName().startsWith(filePattern)) {
                        instrument(file);
                        instrumentedFileCount++;
                    }
                }
            }
        }
    }
    log.info("Instrumented " + instrumentedFileCount + " files.");
}

From source file:org.mycontroller.standalone.utils.McServerFileUtils.java

public static LogFile getLogUpdate(Long lastKnownPosition, Long lastNPosition) {
    if (lastNPosition != null && appLogFile.length() > lastNPosition) {
        lastKnownPosition = appLogFile.length() - lastNPosition;
    } else if (lastKnownPosition != null && appLogFile.length() <= lastKnownPosition) {
        return LogFile.builder().lastKnownPosition(lastKnownPosition).build();
    }/*from ww  w .  j av  a 2  s . co  m*/
    if (lastKnownPosition == null) {
        lastKnownPosition = 0L;
    }

    //Set maximum limit
    if ((appLogFile.length() - lastKnownPosition) > MAX_POSITION_LIMIT) {
        lastKnownPosition = appLogFile.length() - MAX_POSITION_LIMIT;
    }

    logBuilder.setLength(0);
    // Reading and writing file
    RandomAccessFile readFileAccess = null;
    try {
        readFileAccess = new RandomAccessFile(appLogFile, "r");
        readFileAccess.seek(lastKnownPosition);
        String log = null;
        while ((log = readFileAccess.readLine()) != null) {
            logBuilder.append(log).append("\n");
        }
        lastKnownPosition = readFileAccess.getFilePointer();
    } catch (FileNotFoundException ex) {
        _logger.error("Error,", ex);
    } catch (IOException ex) {
        _logger.error("Error,", ex);
    } finally {
        if (readFileAccess != null) {
            try {
                readFileAccess.close();
            } catch (IOException ex) {
                _logger.error("Error,", ex);
            }
        }
    }
    return LogFile.builder().lastKnownPosition(lastKnownPosition).data(logBuilder.toString()).build();
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/** Skip to the next line after the given position by
 * reading a line.  Note that if the position is at the start
 * of a line, it will go to the next line.
 *
 * @param in A file to read from/*from   www  .j a v  a  2  s  .  c  om*/
 * @param pos The position to start at.
 * @return A new position in the file.  The file's pointer (as given by
 * getFilePointer()) is updated to match.
 * @throws IOException If some I/O error occurs
 */
private static long skipToLine(RandomAccessFile in, long pos) throws IOException {
    in.seek(pos);
    in.readLine();
    return in.getFilePointer();
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/**
 * Return the index of the first line in the file to match 'find'. If the
 * lines in the file are roughly equal length, it reads
 * O(sqrt(n)) lines, where n is the distance from matchingline to the first
 * line.//from w  ww .j a v  a2 s  . c  om
 *
 * @param in
 *            The file to search in
 * @param find
 *            The string to match against the first line
 * @param matchingline
 *            The index to start searching from.  This index must be at
 *            the start of a line that matches 'find'
 * @return The offset into the file of the first line matching 'find'.
 *         Guaranteed to be <= matchingline.
 * @throws IOException If the matchingLine < 0 or some I/O error occurs.
 */
private static long findFirstLine(RandomAccessFile in, String find, long matchingline) throws IOException {
    in.seek(matchingline);
    String line = in.readLine();
    if (line == null || compare(line, find) != 0) {
        final String msg = "Internal: Called findFirstLine without a " + "matching line in '" + in + "' byte "
                + matchingline;
        log.warn(msg);
        throw new ArgumentNotValid(msg);
    }
    // Skip backwards in quadratically increasing steps.
    int linelength = line.length();
    long offset = linelength;
    for (int i = 1; matchingline - offset > 0; i++, offset = i * i * linelength) {
        skipToLine(in, matchingline - offset);
        line = in.readLine();
        if (line == null || compare(line, find) != 0) {
            break;
        }
    }
    // Either found start-of-file or a non-matching line
    long pos;
    if (matchingline - offset <= 0) {
        pos = 0;
        in.seek(0);
    } else {
        pos = in.getFilePointer();
    }
    // Seek forwards line by line until the first matching line.
    // This takes no more than sqrt(n) steps since we know there is
    // a matching line that far away by the way we skipped to here.
    while ((line = in.readLine()) != null) {
        if (compare(line, find) == 0) {
            return pos;
        }
        pos = in.getFilePointer();
    }

    return -1;
}

From source file:ValidateLicenseHeaders.java

/**
 * Read the first comment upto the package ...; statement
 * /* w w w .  j  a  va 2 s  .c o m*/
 * @param javaFile
 */
static void parseHeader(File javaFile) throws IOException {
    totalCount++;
    RandomAccessFile raf = new RandomAccessFile(javaFile, "rw");
    String line = raf.readLine();
    StringBuffer tmp = new StringBuffer();
    long endOfHeader = 0;
    boolean packageOrImport = false;
    while (line != null) {
        long nextEOH = raf.getFilePointer();
        line = line.trim();
        // Ignore any single line comments
        if (line.startsWith("//")) {
            line = raf.readLine();
            continue;
        }

        // If this is a package/import/class/interface statement break
        if (line.startsWith("package") || line.startsWith("import") || line.indexOf("class") >= 0
                || line.indexOf("interface") >= 0) {
            packageOrImport = true;
            break;
        }

        // Update the current end of header marker
        endOfHeader = nextEOH;

        if (line.startsWith("/**"))
            tmp.append(line.substring(3));
        else if (line.startsWith("/*"))
            tmp.append(line.substring(2));
        else if (line.startsWith("*"))
            tmp.append(line.substring(1));
        else
            tmp.append(line);
        tmp.append(' ');
        line = raf.readLine();
    }
    raf.close();

    if (tmp.length() == 0 || packageOrImport == false) {
        addDefaultHeader(javaFile);
        return;
    }

    String text = tmp.toString();
    // Replace all duplicate whitespace with a single space
    text = text.replaceAll("[\\s*]+", " ");
    text = text.toLowerCase().trim();
    // Replace any copyright date0-date1,date2 with copyright ...
    text = text.replaceAll(COPYRIGHT_REGEX, "...");
    if (tmp.length() == 0) {
        addDefaultHeader(javaFile);
        return;
    }
    // Search for a matching header
    boolean matches = false;
    String matchID = null;
    Iterator iter = licenseHeaders.entrySet().iterator();
    escape: while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        List list = (List) entry.getValue();
        Iterator jiter = list.iterator();
        while (jiter.hasNext()) {
            LicenseHeader lh = (LicenseHeader) jiter.next();
            if (text.startsWith(lh.text)) {
                matches = true;
                matchID = lh.id;
                lh.count++;
                lh.usage.add(javaFile);
                if (log.isLoggable(Level.FINE))
                    log.fine(javaFile + " matches copyright key=" + key + ", id=" + lh.id);
                break escape;
            }
        }
    }
    text = null;
    tmp.setLength(0);
    if (matches == false)
        invalidheaders.add(javaFile);
    else if (matchID.startsWith("jboss") && matchID.endsWith("#0") == false) {
        // This is a legacy jboss head that needs to be updated to the default
        replaceHeader(javaFile, endOfHeader);
        jbossCount++;
    }
}

From source file:net.sourceforge.doddle_owl.data.JpnWordNetDic.java

private static long getDataFp(long fp, RandomAccessFile indexFile) {
    try {//from   w  w  w  .  j  av a  2s . co m
        indexFile.seek(fp);
        return Long.valueOf(indexFile.readLine());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return -1;
}

From source file:count.ly.messaging.CrashDetails.java

private static long getTotalRAM() {
    if (totalMemory == 0) {
        RandomAccessFile reader = null;
        String load = null;//from  ww w. j a  va  2 s . c  om
        try {
            reader = new RandomAccessFile("/proc/meminfo", "r");
            load = reader.readLine();

            // Get the Number value from the string
            Pattern p = Pattern.compile("(\\d+)");
            Matcher m = p.matcher(load);
            String value = "";
            while (m.find()) {
                value = m.group(1);
            }
            reader.close();

            totalMemory = Long.parseLong(value) / 1024;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return totalMemory;
}

From source file:ly.count.android.sdk.CrashDetails.java

private static long getTotalRAM() {
    if (totalMemory == 0) {
        RandomAccessFile reader = null;
        String load = null;/* w  ww.  jav  a  2  s.c  o m*/
        try {
            reader = new RandomAccessFile("/proc/meminfo", "r");
            load = reader.readLine();

            // Get the Number value from the string
            Pattern p = Pattern.compile("(\\d+)");
            Matcher m = p.matcher(load);
            String value = "";
            while (m.find()) {
                value = m.group(1);
            }
            try {
                totalMemory = Long.parseLong(value) / 1024;
            } catch (NumberFormatException ex) {
                totalMemory = 0;
            }
        } catch (IOException ex) {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
            ex.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    }
    return totalMemory;
}