Java RandomAccessFile Read readLine(RandomAccessFile file, long position, int trim)

Here you can find the source of readLine(RandomAccessFile file, long position, int trim)

Description

Reads a line truncating it as needed.

License

Apache License

Declaration


public static String readLine(RandomAccessFile file, long position, int trim) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.RandomAccessFile;

public class Main {
    /**/*www .  ja v  a 2s. c o  m*/
     * Reads a line truncating it as needed.
     * Assumes that hasPrevious was previously called.
     */

    public static String readLine(RandomAccessFile file, long position, int trim) throws IOException {
        StringBuilder input = new StringBuilder();
        int c = -1;
        boolean eol = false;
        int count = 0;

        file.seek(position);

        while (!eol) {
            switch (c = file.read()) {
            case -1:
            case '\n':
                eol = true;
                break;
            case '\r':
                eol = true;
                long cur = file.getFilePointer();
                if ((file.read()) != '\n') {
                    file.seek(cur);
                }
                break;
            default:
                if (-1 != trim && count >= trim) {
                    eol = true;
                    break;
                }
                input.append((char) c);
                count++;
                break;
            }
        }

        if ((c == -1) && (input.length() == 0)) {
            return null;
        }

        return input.toString();
    }
}

Related

  1. readFile(String filename)
  2. readFile(String filePath)
  3. readFileByRandomAccess(String fileName)
  4. readFileBytes(final File file)
  5. readFileFully(File f)
  6. readLongLittleEndian( RandomAccessFile randomAccessFile)