Implementar el seguimiento del puntero de archivo en Java

necesidad

Use el flujo de lectura de archivos para realizar el retroceso del puntero del archivo. Lea cada línea de datos en el archivo de texto, registre la posición del último carácter leído y el siguiente carácter que se leerá, y genere la última línea leída.

entorno de laboratorio

Jdk8,IDEA

procedimiento del experimento

tren de pensamiento

Este experimento usa las funciones remark, reset y readline en BufferReader:
1. remark() : marca la posición del carácter, si nunca ha sido marcado, marcará la posición del primer carácter del archivo por defecto

  /**
     * Marks the present position in the stream.  Subsequent calls to reset()
     * will attempt to reposition the stream to this point.
     *
     * @param readAheadLimit   Limit on the number of characters that may be
     *                         read while still preserving the mark. An attempt
     *                         to reset the stream after reading characters
     *                         up to this limit or beyond may fail.
     *                         A limit value larger than the size of the input
     *                         buffer will cause a new buffer to be allocated
     *                         whose size is no smaller than limit.
     *                         Therefore large values should be used with care.
     *
     * @exception  IllegalArgumentException  If {@code readAheadLimit < 0}
     * @exception  IOException  If an I/O error occurs
     */
    public void mark(int readAheadLimit) throws IOException {
    
    
        if (readAheadLimit < 0) {
    
    
            throw new IllegalArgumentException("Read-ahead limit < 0");
        }
        synchronized (lock) {
    
    
            ensureOpen();
            this.readAheadLimit = readAheadLimit;
            markedChar = nextChar;
            markedSkipLF = skipLF;
        }
    }

2.reset() : Vuelve a la última posición marcada

/**
 * Resets the stream to the most recent mark.
 *
 * @exception  IOException  If the stream has never been marked,
 *                          or if the mark has been invalidated
 */
public void reset() throws IOException {
    
    
    synchronized (lock) {
    
    
        ensureOpen();
        if (markedChar < 0)
            throw new IOException((markedChar == INVALIDATED)
                                  ? "Mark invalid"
                                  : "Stream not marked");
        nextChar = markedChar;
        skipLF = markedSkipLF;
    }
}

3.readline() : Lee una línea de datos (desde la ubicación del puntero del archivo)

código fuente

    public static void readTxtFile3(String fileName) throws IOException {
    
    
        int past_pos = 1; // 文件指针上一次所在位置
        int cur_pos = 1; // 文件指针当前所在位置(就是下一个要读取的字符的位置)
        int cur_lineNumber = 1;
        InputStreamReader fr = new InputStreamReader(new FileInputStream(fileName), "UTF-8"); // 指定以UTF-8编码读入
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        while ((line = br.readLine()) != null) {
    
      // 文件未到文件尾
            past_pos = cur_pos;
            cur_pos += line.length();
            br.mark(past_pos);
            br.reset();
            System.out.println("第 " + cur_lineNumber + " 行: " + past_pos + "," + cur_pos);
            System.out.println(line);
            cur_lineNumber++;
        }
    }

    public static void main(String[] args) throws IOException {
    
    
        String fileName = "D:\\data\\pdata\\all_person_info.txt"; // 读取文件
        int totalNo = getTotalLines(fileName);  // 获取文件的内容的总行数
        System.out.println("本文总共有:" + totalNo + "行");
        ReadFile2.readTxtFile3(fileName);
    }

resultado de la operación

contenido del documento
Resultados de la

insuficiente

Los documentos oficiales de estas funciones también mencionaron que si el archivo es demasiado grande, es decir, la cantidad de caracteres excede el rango del tipo int, la función remark() fallará. En cuanto a cómo resolverlo, debería poder para usar el objeto de flujo de entrada de bytes de archivo! ! !
Cómo lograrlo, ¡consulte mi próximo artículo!

Supongo que te gusta

Origin blog.csdn.net/dubulingbo/article/details/106996696
Recomendado
Clasificación