日期:2014-05-20  浏览次数:20872 次

java 读取文件指定行的内容
比如现有一d:\11.txt,内容为
<NUMBER 2>
ddddddddddd
fffffffffff
ggggggggggg
hhhhhhhhhhh
...
如何读取指定行的内容? 查看了API,LineNumberInputStream类似乎可以解决这个问题,但是函数getLineNumber()得到的只是当前的行号。
另外一个思路就是:按行读取文件内容,把每行作为String存入ArrayList<String>中,然后在通过get(index)获取指定行的内容。功能是实现了,但是感觉效率不高,尤其是对内容比较大的文本的读取。

网上找到的一个程序:
Java code
/** 
 * 读取文件指定行。 
 */
public class ReadSelectedLine {
//     读取文件指定行。 
    static void readAppointedLineNumber(File sourceFile, int lineNumber) throws IOException {
        FileReader in = new FileReader(sourceFile);
        LineNumberReader reader = new LineNumberReader(in);
        String s = reader.readLine();
        
        if (lineNumber < 0 || lineNumber > getTotalLines(sourceFile)) {
            System.out.println("不在文件的行数范围之内。");
        }

        {
        while (s != null) {
            System.out.println("当前行号为:" + reader.getLineNumber());
            
            System.out.println(s);
            System.exit(0);
            s = reader.readLine();
        }
        }
        reader.close();
        in.close();
    }

    // 文件内容的总行数。 
    static int getTotalLines(File file) throws IOException {
        FileReader in = new FileReader(file);
        LineNumberReader reader = new LineNumberReader(in);
        String s = reader.readLine();
        int lines = 0;
        while (s != null) {
            lines++;
            s = reader.readLine();
        }
        reader.close();
        in.close();
        return lines;
    }
    
    public static void main(String[] args) throws IOException {
        
        // 读取文件 
        File sourceFile = new File("d:/11.txt");
        // 获取文件的内容的总行数 
        int totalNo = getTotalLines(sourceFile);
        System.out.println("There are "+totalNo+ " lines in the text!");
        
        // 指定读取的行号 
        int lineNumber = 2;
        
        // 读取指定的行 
        readAppointedLineNumber(sourceFile, lineNumber);
        
        
        
    }

    
}

在这个程序中, 函数readAppointedLineNumber(File sourceFile, int lineNumber)的第二个参数好象起到读取指定行内容的作用 

再就是如何让程序直接从文本的第二行开始读取呢?

------解决方案--------------------
用随机文件操作。有个类似叫RandomAccessFile的文件吧。不记得正确名字是什么呢,反应有Random Access这两个词的。
------解决方案--------------------
每行长度相等时,可以这样做
Java code
import java.io.*;

public class Test
{
    private static final int line = 4;//每行的长度,包括\t或\r\t,注意区别
    
    public static void main(String[] args) throws Exception
    {
        RandomAccessFile raf = new RandomAccessFile("a.txt", "r");
        int lineIndex = 3;
        raf.seek(line * lineIndex);
        System.out.println(raf.readLine());
    }
}

------解决方案--------------------
我给楼主提供一个空间换时间的方法。文档的换行无论是\r\n还是\n你都可以用\n来分隔。然后分隔完成的字符串数组0 1 2就是第1,2,3行,读取指定一行的内容直接取【i-1】数组内容即可。