在 Java 中从文本文件中读取特定行

2022-09-04 21:24:31

从文本文件中提取特定行号数据的最有效方法是什么?例如,如果我使用 Scanner 分析文件,是否首先必须创建一个长度与文本文件中的总行数匹配的数组?

如果文本文件有 30 行,而我只想使用第 3、8 和 12 行,有没有办法专门只读取这些行?


答案 1

这是你如何做到的:

import java.io.*;

public class Test {
public static void main(String [] args) {

    // The name of the file to open.
    String fileName = "temp.txt";
    int counter = 0;

    // This will reference one line at a time
    String line = null;
    FileReader fileReader = null;

    try {
        // FileReader reads text files in the default encoding.
        fileReader = 
            new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = 
            new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            counter++;
            if(counter == 3 || counter == 8 || counter == 12)
            {
               // do your code
            }
        }   

    }
    catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                  
        // Or we could just do this: 
        // ex.printStackTrace();
    }
    finally
    {
        if(fileReader != null){
           // Always close files.
           bufferedReader.close();            
        }
    }
}
}

答案 2

(这只是你程序的一部分,不完全是你的程序)

int counter 0 =;
BufferedReader br = new BufferedReader(new FileReader(file));  
String line;  
while ((line = br.readLine()) != null) {  
   // process the line.  
   counter++;

   switch(counter){  
    case 3:  
       \\ do your code for line no 3  
       break;  
    case 8:  
       \\ do your code for line no 8  
       break;  
    case 12:  
       \\ do your code for line no 12  
       break;  
   }  
}    
br.close();  

推荐