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