如何使用Java文件中的特定行号读取特定行?

如何使用Java文件中的特定行号读取特定行?,java,file-io,Java,File Io,在Java中,是否有任何方法可以从文件中读取特定行?例如,读取第32行或任何其他行号。除非您事先了解文件中的行,否则如果不读取前31行,就无法直接访问第32行 这适用于所有语言和所有现代文件系统 因此,在找到第32行之前,您只需简单地读取行。如果您谈论的是一个文本文件,那么在不读取它前面的所有行之前,实际上是没有办法做到这一点的-毕竟,行是由新行的存在决定的,因此必须读取它 使用支持readline的流,只需读取前X-1行并转储结果,然后处理下一行 据我所知不是这样,但是您可以使用Buffere

在Java中,是否有任何方法可以从文件中读取特定行?例如,读取第32行或任何其他行号。

除非您事先了解文件中的行,否则如果不读取前31行,就无法直接访问第32行

这适用于所有语言和所有现代文件系统


因此,在找到第32行之前,您只需简单地读取行。

如果您谈论的是一个文本文件,那么在不读取它前面的所有行之前,实际上是没有办法做到这一点的-毕竟,行是由新行的存在决定的,因此必须读取它


使用支持readline的流,只需读取前X-1行并转储结果,然后处理下一行

据我所知不是这样,但是您可以使用BufferedReader的readline()函数在前31行中循环,什么也不做

FileInputStream fs= new FileInputStream("someFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < 31; ++i)
  br.readLine();
String lineIWant = br.readLine();
FileInputStream fs=newfileinputstream(“someFile.txt”);
BufferedReader br=新的BufferedReader(新的InputStreamReader(fs));
对于(int i=0;i<31;++i)
br.readLine();
字符串lineIWant=br.readLine();

否,除非在该文件格式中,行长是预先确定的(例如,所有具有固定长度的行),否则您必须逐行迭代以计算它们。

当然,Joachim是正确的,Chris的另一个实现(仅适用于小文件,因为它加载整个文件)可能是使用Apache的commons io(虽然可以说,您可能不想为此引入新的依赖项,但如果您发现它对其他东西也有用,那么它可能是有意义的)

例如:

String line32 = (String) FileUtils.readLines(file).get(31);

,java.lang.String)

您可以使用LineNumberReader而不是BufferedReader。浏览api。您可以找到setLineNumber和getLineNumber方法。

您还可以查看LineNumberReader,BufferedReader的子类。除了readline方法外,它还有setter/getter方法来访问行号。从文件中读取数据时,跟踪读取的行数非常有用。

您可以尝试(Apache许可证2.0)。IndexedFileReader类有一个名为的方法,该方法返回一个SortedMap,其键是行号,值是读取的行

例如:

File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);

lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));      
上面的示例读取由以下格式的50行组成的文本文件:

[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN

Disclamer:我写了这个库

他们都错了,我只是在大约10秒钟内写了这个。 有了它,我就可以在main方法中调用object.getQuestion(“linenumber”)来返回我想要的任何一行

public class Questions {

File file = new File("Question2Files/triviagame1.txt");

public Questions() {

}

public String getQuestion(int numLine) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";
    for(int i = 0; i < numLine; i++) {
        line = br.readLine();
    }
    return line; }}
公开课问题{
File File=新文件(“Question2Files/triviagame1.txt”);
公众问题(){
}
公共字符串getQuestion(int numLine)引发IOException{
BufferedReader br=新的BufferedReader(新文件读取器(文件));
字符串行=”;
for(int i=0;i
对于小文件:

String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
    line32 = lines.skip(31).findFirst().get();
}
对于大文件:

String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
    line32 = lines.skip(31).findFirst().get();
}
try(streamlines=Files.lines(path.get(“file.txt”)){
line32=lines.skip(31).findFirst().get();
}
公共字符串读取行(int行){
FileReader tempFileReader=null;
BufferedReader tempBufferedReader=null;
尝试{tempFileReader=newfilereader(textFile);
tempBufferedReader=新的BufferedReader(tempFileReader);
}捕获(例外e){}
字符串returnStr=“ERROR”;
对于(int i=0;i
这对我很有用: 我已经把这个问题的答案结合起来了

但不是返回字符串,而是返回字符串的LinkedList。然后我可以选择我想要的线

public static LinkedList<String> readFromAssets(Context context, String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
    LinkedList<String>linkedList = new LinkedList<>();
    // do reading, usually loop until end of file reading
    StringBuilder sb = new StringBuilder();
    String mLine = reader.readLine();
    while (mLine != null) {
        linkedList.add(mLine);
        sb.append(mLine); // process line
        mLine = reader.readLine();


    }
    reader.close();
    return linkedList;
}
公共静态LinkedList readFromAssets(上下文,字符串文件名)引发IOException{
BufferedReader=new BufferedReader(new InputStreamReader(context.getAssets().open(filename));
LinkedListlinkedList=新建LinkedList();
//进行读取,通常循环直到文件读取结束
StringBuilder sb=新的StringBuilder();
字符串mLine=reader.readLine();
while(mLine!=null){
linkedList.add(mLine);
sb.append(mLine);//工艺线
mLine=reader.readLine();
}
reader.close();
返回linkedList;
}
另一种方法

try (BufferedReader reader = Files.newBufferedReader(
        Paths.get("file.txt"), StandardCharsets.UTF_8)) {
    List<String> line = reader.lines()
                              .skip(31)
                              .limit(1)
                              .collect(Collectors.toList());

    line.stream().forEach(System.out::println);
}
try(BufferedReader=Files.newBufferedReader)(
path.get(“file.txt”)、StandardCharsets.UTF_(8)){
列表行=reader.lines()
.skip(31)
.限额(1)
.collect(Collectors.toList());
line.stream().forEach(System.out::println);
}
您可以使用skip()函数从开头跳过行

public static void readFile(String filePath, long lineNum) {
    List<String> list = new ArrayList<>();
    long totalLines, startLine = 0;

    try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
        totalLines = Files.lines(Paths.get(filePath)).count();
        startLine = totalLines - lineNum;
        // Stream<String> line32 = lines.skip(((startLine)+1));

        list = lines.skip(startLine).collect(Collectors.toList());
        // lines.forEach(list::add);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    list.forEach(System.out::println);

}
publicstaticvoidreadfile(stringfilepath,longlinenum){
列表=新的ArrayList();
长总线,短线=0;
try(streamlines=Files.lines(path.get(filePath))){
totalines=Files.lines(path.get(filePath)).count();
startLine=totalLines-lineNum;
//Stream line32=行。跳过(((行)+1));
list=lines.skip(startLine).collect(Collectors.toList());
//lines.forEach(列表::add);
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
list.forEach(System.out::println);
}

尽管如其他答案所述,在不知道偏移量(指针)的情况下,不可能到达准确的直线。因此,我通过创建一个临时索引文件来实现这一点,该文件将存储每行的偏移量值。如果文件足够小,您可以将索引(偏移量)存储在内存中,而不需要单独的文件

偏移量可以是
import java.nio.file.Files;

import java.nio.file.Paths;

public class FileWork 
{

    public static void main(String[] args) throws IOException {

        String line = Files.readAllLines(Paths.get("D:/abc.txt")).get(1);

        System.out.println(line);  
    }

}
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
String line;
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
    line = lines.skip(n).findFirst().get();
}
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    for (int i = 0; i < n; i++)
        br.readLine();
    line = br.readLine();
}
public class TextFileAssignmentOct {
    
    private void readData(int rowNum, BufferedReader br) throws IOException {
        int n=1;                                    //Line number starts from 1
        String row;
        while((row=br.readLine()) != null)  {       // Reads every line
            if (n == rowNum) {                      // When Line number matches with which you want to read
                System.out.println(row);
            }
            n++;                                    //This increments Line number
        }
    }

    public static void main(String[] args) throws IOException {
        File f = new File("../JavaPractice/FileRead.txt");
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        
        TextFileAssignmentOct txf = new TextFileAssignmentOct();
        txf.readData(4, br);    //Read a Specific Line using Line number and Passing buffered reader
    }
}