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.nuxeo.connect.update.task.standalone.commands.Copy.java

/**
 * @param doOverwrite/*w w w  .  j  a va2s.c  o  m*/
 * @since 5.5
 */
protected Command doCopy(Task task, Map<String, String> prefs, File fileToCopy, File dst, boolean doOverwrite)
        throws PackageException {
    String dstmd5;
    File bak = null;
    CompositeCommand rollbackCommand = new CompositeCommand();
    if (fileToCopy.isDirectory()) {
        if (fileToCopy != file) {
            dst = new File(dst, fileToCopy.getName());
        }
        dst.mkdirs();
        for (File childFile : fileToCopy.listFiles()) {
            rollbackCommand.addCommand(doCopy(task, prefs, childFile, dst, doOverwrite));
        }
        return rollbackCommand;
    }
    if (dst.isDirectory()) {
        dst = new File(dst, fileToCopy.getName());
    }
    try {
        FileMatcher filenameMatcher = FileMatcher.getMatcher("{n:.*-}[0-9]+.*\\.jar");
        boolean isVersionnedJarFile = filenameMatcher.match(fileToCopy.getName());
        if (isVersionnedJarFile) {
            log.warn(String.format(
                    "Use of the <copy /> command on JAR files is not recommended, prefer using <update /> command to ensure a safe rollback. (%s)",
                    fileToCopy.getName()));
        }
        if (isVersionnedJarFile && (overwriteIfNewerVersion || upgradeOnly)) {
            // Compare source and destination versions set in filename
            FileVersion fileToCopyVersion, dstVersion = null;
            String filenameWithoutVersion = filenameMatcher.getValue();
            FileMatcher versionMatcher = FileMatcher.getMatcher(filenameWithoutVersion + "{v:[0-9]+.*}\\.jar");
            // Get new file version
            if (versionMatcher.match(fileToCopy.getName())) {
                fileToCopyVersion = new FileVersion(versionMatcher.getValue());
                // Get original file name and version
                File dir = dst.getParentFile();
                File[] list = dir.listFiles();
                if (list != null) {
                    for (File f : list) {
                        if (versionMatcher.match(f.getName())) {
                            dst = f;
                            dstVersion = new FileVersion(versionMatcher.getValue());
                            break;
                        }
                    }
                }
                if (dstVersion == null) {
                    if (upgradeOnly) {
                        return null;
                    }
                } else if (fileToCopyVersion.greaterThan(dstVersion)) {
                    // backup dst and generate rollback command
                    File oldDst = dst;
                    dst = new File(dst.getParentFile(), fileToCopy.getName());
                    File backup = IOUtils.backup(task.getPackage(), oldDst);
                    rollbackCommand.addCommand(new Copy(backup, oldDst, null, false));
                    // Delete old dst as its name differs from new version
                    oldDst.delete();
                } else if (fileToCopyVersion.isSnapshot() && fileToCopyVersion.equals(dstVersion)) {
                    doOverwrite = true;
                } else if (!doOverwrite) {
                    log.info("Ignore " + fileToCopy + " because not newer than " + dstVersion
                            + " and 'overwrite' is set to false.");
                    return null;
                }
            }
        }
        if (dst.exists()) { // backup the destination file if exist.
            if (!doOverwrite && !append) { // force a rollback
                throw new PackageException(
                        "Copy command has overwrite flag on false but destination file exists: " + dst);
            }
            if (task instanceof UninstallTask) {
                // no backup for uninstall task
            } else if (append) {
                bak = IOUtils.backup(task.getPackage(), fileToCopy);
            } else {
                bak = IOUtils.backup(task.getPackage(), dst);
            }
        } else { // target file doesn't exists - it will be created
            dst.getParentFile().mkdirs();
        }

        // copy the file - use getContentToCopy to allow parameterization
        // for subclasses
        String content = getContentToCopy(fileToCopy, prefs);
        if (content != null) {
            if (append && dst.exists()) {
                RandomAccessFile rfile = new RandomAccessFile(dst, "r");
                try {
                    rfile.seek(dst.length());
                    if (!"".equals(rfile.readLine())) {
                        content = System.getProperty("line.separator") + content;
                    }
                } catch (IOException e) {
                    log.error(e);
                } finally {
                    rfile.close();
                }
            }
            FileUtils.writeFile(dst, content, append);
        } else {
            File tmp = new File(dst.getPath() + ".tmp");
            FileUtils.copy(fileToCopy, tmp);
            if (!tmp.renameTo(dst)) {
                tmp.delete();
                FileUtils.copy(fileToCopy, dst);
            }
        }
        // check whether the copied or restored file was the launcher
        if (dst.getName().equals(LAUNCHER_JAR) || fileToCopy.getName().equals(LAUNCHER_JAR)) {
            Environment env = Environment.getDefault();
            env.setProperty(LAUNCHER_CHANGED_PROPERTY, "true");
        }
        // get the md5 of the copied file.
        dstmd5 = IOUtils.createMd5(dst);
    } catch (IOException e) {
        throw new PackageException("Failed to copy " + fileToCopy, e);
    }
    if (bak == null) { // no file was replaced
        rollbackCommand.addCommand(new Delete(dst, dstmd5, removeOnExit));
    } else if (append) {
        rollbackCommand.addCommand(new UnAppend(bak, dst));
    } else {
        rollbackCommand.addCommand(new Copy(bak, dst, dstmd5, true));
    }
    return rollbackCommand;
}

From source file:com.datatorrent.flume.storage.HDFSStorageTest.java

@Test
public void testCleanup() throws IOException {
    RandomAccessFile r = new RandomAccessFile(testMeta.testFile, "r");
    r.seek(0);/*from w  ww .j a v a2s.co  m*/
    byte[] b = r.readLine().getBytes();
    storage.store(new Slice(b, 0, b.length));
    byte[] val = storage.store(new Slice(b, 0, b.length));
    storage.flush();
    storage.clean(val);
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    boolean exists = fs.exists(new Path(STORAGE_DIRECTORY + "/" + "0"));
    Assert.assertEquals("file should not exist", false, exists);
    r.close();
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextDataFluxSingle(File file) {
    try {//from www.  ja v a  2  s  . c om
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        while (!data.startsWith("3) Flux Image Data")) {
            System.out.println(data);
            data = in.readLine();
        }
        in.readLine();
        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][] holder = new short[wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        // Skip over the heading values

        sIn.reset();

        for (int y = 0; y < high; y++) {
            System.out.println(sIn.nextInt());
            try {
                for (int x = 0; x < wide; x++) {
                    holder[x][y] = sIn.nextShort();
                }
            } catch (Throwable e) {

            }

        }
        addData(new Date(), holder);

        FrameFactroy.getFrame(new DynamicRangeImage(holder));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.fragments.EventGeneratorFragment.java

private float readCPUUsage() {
    try {//ww w  .  jav  a2 s .co  m
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {
        }

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" ");

        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextData(File file) {
    try {/*  w  w  w.  ja  v  a  2s.  c o m*/
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // Time Data
        in.readLine();
        String timeDataInput = in.readLine();
        String totalImagesInput = in.readLine();
        in.readLine();
        in.readLine();
        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        try {
            tot = (new Scanner(totalImagesInput.split(":")[1])).nextInt();
        } catch (Exception e) {

        }
        System.out.println(wide + "," + high);
        // Parse timeInformation
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss (dd/MM/yy)");
        Date startTime = null;
        try {
            startTime = format.parse(startTimeInput.split(": ")[1]);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String[] frameTimeData = timeDataInput.split("information:")[1].split(",");

        Date[] timeInfo = new Date[tot];
        for (int i = 0; i < frameTimeData.length - 1; i++) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(startTime);
            String dat = (frameTimeData[i]);
            String[] timeVals = dat.split(":");

            int hour = Integer.parseInt(StringOperations.removeNonNumber(timeVals[0]));
            int min = Integer.parseInt(StringOperations.removeNonNumber(timeVals[1]));
            int sec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[2]));
            int msec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[3]));

            cal.add(Calendar.HOUR_OF_DAY, hour);
            cal.add(Calendar.MINUTE, min);
            cal.add(Calendar.SECOND, sec);
            cal.add(Calendar.MILLISECOND, msec);
            timeInfo[i] = cal.getTime();
        }

        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][][] holder = new short[tot][wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        for (int i = 0; i < tot; i++) {
            // Skip over the heading values
            stat.setStatusMessage("Loading " + i + " of " + tot);
            sIn.useDelimiter("\n");
            sIn.next();
            sIn.next();
            sIn.next();
            if (i != 0) {
                sIn.next();
            }
            sIn.reset();
            for (int y = 0; y < high; y++) {
                stat.setValue(y);
                sIn.nextInt();
                for (int x = 0; x < wide; x++) {
                    holder[i][x][y] = sIn.nextShort();
                }

            }
            addData(timeInfo[i], holder[i]);
        }

        // FrameFactroy.getFrame(new DynamicRangeImage(data[0]));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.datatorrent.flume.storage.HDFSStorageTest.java

@Test
public void testNext() throws IOException {
    RandomAccessFile r = new RandomAccessFile(testMeta.testFile, "r");
    r.seek(0);/* ww  w . jav a  2 s . co m*/
    Assert.assertNull(storage.retrieve(new byte[8]));
    byte[] b = r.readLine().getBytes();
    storage.store(new Slice(b, 0, b.length));
    byte[] b1 = r.readLine().getBytes();
    storage.store(new Slice(b1, 0, b1.length));
    storage.store(new Slice(b, 0, b.length));
    storage.flush();
    storage.store(new Slice(b1, 0, b1.length));
    storage.store(new Slice(b, 0, b.length));
    storage.flush();
    byte[] data = storage.retrieve(new byte[8]);
    byte[] tempData = new byte[data.length - 8];
    System.arraycopy(data, 8, tempData, 0, tempData.length);
    Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData));
    data = storage.retrieveNext();
    tempData = new byte[data.length - 8];
    System.arraycopy(data, 8, tempData, 0, tempData.length);
    Assert.assertEquals("matched the stored value with retrieved value", new String(b1), new String(tempData));
    data = storage.retrieveNext();
    tempData = new byte[data.length - 8];
    System.arraycopy(data, 8, tempData, 0, tempData.length);
    Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData));
    r.close();
}

From source file:at.tuwien.minimee.util.TopParser.java

/**
 * The process ID is in the last line of the file and looks like follows:
 * monitored_pid= 6738 //www. j a v  a2s . co m
 * 
 * @param input
 * @return
 * @throws Exception
 */
private Integer findPid() throws Exception {

    Integer pid = new Integer(0);

    // we open the file
    RandomAccessFile f = new RandomAccessFile(file, "r");

    try {

        long size = f.length();

        f.seek(size - 2);

        // we search the file reverse for '='
        byte[] b = new byte[1];
        for (long i = size - 2; i >= 0; i--) {
            f.seek(i);
            f.read(b);
            if (b[0] == '=') {
                break;
            }
        }

        String line = f.readLine().trim();

        pid = new Integer(line);

    } finally {
        // this is important, RandomAccessFile doesn't close the file handle by default!
        // if close isn't called, you'll get very soon 'too many open files'
        f.close();
    }

    return pid;
}

From source file:com.kyne.webby.rtk.modules.WebbyRTKModule.java

public List<String> readConsoleLog(final LogMode logMode) {
    final List<String> logLines = new ArrayList<String>();
    String line = "";

    File logFile = null;/*from   www  .  jav  a  2 s .  c om*/
    if (logMode == LogMode.NEW) {
        logFile = new File("logs/latest.log");
    } else if (logMode == LogMode.OLD) {
        logFile = new File("server.log");
    } else {
        throw new UnsupportedOperationException("Unsupported log mode " + logMode);
    }

    if (!logFile.exists()) {
        LogHelper.error("Unable to find the log file at " + logFile.getAbsolutePath());
        return Arrays.asList("Unable to find the log file");
    }

    RandomAccessFile randomFile = null;
    try {
        randomFile = new RandomAccessFile(logFile, "r");
        final long linesToRead = 100;
        final long fileLength = randomFile.length();
        long startPosition = fileLength - (linesToRead * 100);
        if (startPosition < 0) {
            startPosition = 0;
        }
        randomFile.seek(startPosition);
        while ((line = randomFile.readLine()) != null) {
            logLines.add(line.replace("[0;30;22m", "").replace("[0;34;22m", "").replace("[0;32;22m", "")
                    .replace("[0;36;22m", "").replace("[0;31;22m", "").replace("[0;35;22m", "")
                    .replace("[0;33;22m", "").replace("[0;37;22m", "").replace("[0;30;1m", "")
                    .replace("[0;34;1m", "").replace("[0;32;1m", "").replace("[0;36;1m", "")
                    .replace("[0;31;1m", "").replace("[0;35;1m", "").replace("[0;33;1m", "")
                    .replace("[0;37;1m", "").replace("[m", "").replace("[5m", "").replace("[21m", "")
                    .replace("[9m", "").replace("[4m", "").replace("[3m", "").replace("[0;39m", "")
                    .replace("[0m", ""));

        }
    } catch (final IOException e) {
        LogHelper.error("Unable to read server.log", e);
    } finally {
        IOUtils.closeQuietly(randomFile);
    }
    return logLines;
}

From source file:org.artifactory.webapp.wicket.page.logs.SystemLogsViewPanel.java

/**
 * Attemps to continue reading the log file from the last position, and the updates the log path, size and link
 * According to the outcome.//w ww  .ja v  a 2s .c  om
 *
 * @param cleanPanel True if the text container should be cleaned of content. false if not
 * @return String - The newly read content
 */
protected String readLogAndUpdateSize(boolean cleanPanel) {
    if ((lastPointer > systemLogFile.length()) || cleanPanel) {
        lastPointer = 0;
    }
    long size = systemLogFile.length();
    setLogInfo();
    if (lastPointer == size) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    RandomAccessFile logRandomAccessFile = null;
    try {
        logRandomAccessFile = new RandomAccessFile(systemLogFile, "r");

        //If the log file is larger than 100K
        if (lastPointer == 0 && logRandomAccessFile.length() > FIRST_READ_BLOCK_SIZE) {
            //Point to the begining of the last 100K
            lastPointer = logRandomAccessFile.length() - FIRST_READ_BLOCK_SIZE;
        }
        logRandomAccessFile.seek(lastPointer);

        String line;
        while ((line = logRandomAccessFile.readLine()) != null) {
            CharSequence escapedLine = Strings.escapeMarkup(line, false, false);
            sb.append("<div>").append(escapedLine).append("<br/></div>");
        }
        lastPointer = logRandomAccessFile.getFilePointer();

    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    } finally {
        try {
            if (logRandomAccessFile != null) {
                logRandomAccessFile.close();
            }
        } catch (IOException ignore) {
        }
    }
    return sb.toString();
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Read the last line in a file. Note this method is not UTF-8 safe.
 *
 * @param file input file to read last line from.
 * @return The last line in the file (ending newline is irrelevant),
 * returns an empty string if file is empty.
 * @throws ArgumentNotValid on null argument, or file is not a readable
 * file./*ww w .  j  av  a 2 s. c  o  m*/
 * @throws IOFailure on IO trouble reading file.
 */
public static String readLastLine(File file) {
    ArgumentNotValid.checkNotNull(file, "File file");
    if (!file.isFile() || !file.canRead()) {
        final String errMsg = "File '" + file.getAbsolutePath() + "' is not a readable file.";
        log.warn(errMsg);
        throw new ArgumentNotValid(errMsg);
    }
    if (file.length() == 0) {
        return "";
    }
    RandomAccessFile rafile = null;
    try {
        rafile = new RandomAccessFile(file, "r");
        //seek to byte one before end of file (remember we know the file is
        // not empty) - this ensures that an ending newline is not read
        rafile.seek(rafile.length() - 2);
        //now search to the last linebreak, or beginning of file
        while (rafile.getFilePointer() != 0 && rafile.read() != '\n') {
            //search back two, because we just searched forward one to find
            //newline
            rafile.seek(rafile.getFilePointer() - 2);
        }
        return rafile.readLine();
    } catch (IOException e) {
        final String errMsg = "Unable to access file '" + file.getAbsolutePath() + "'";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    } finally {
        try {
            if (rafile != null) {
                rafile.close();
            }
        } catch (IOException e) {
            log.debug("Unable to close file '" + file.getAbsolutePath() + "' after reading", e);
        }
    }
}