簡體   English   中英

如何從文件中讀取N行?

[英]How to read N amount of lines from a file?

我正在嘗試練習從Java文件中讀取文本。 我幾乎不了解如何讀取N行,比如說文件中的前10行,然后將這些行添加到ArrayList

例如,文件包含1-100個數字,就像這樣;

- 1 
- 2 
- 3 
- 4 
- 5 
- 6 
- 7 
- 8 
- 9 
- 10 
- ....

我想讀取前5個數字,所以1,2,3,4,5並將其添加到數組列表中。 到目前為止,這是我設法做的,但是我被困住了,不知道現在該怎么辦。

ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));

for (double i = 0; i <= 5; ++i) {
    // I know I need to add something here so the for loop read through 
    // the file but I have no idea how I can do this
    array.add(i); // This is saying read 1 line and add it to arraylist,
    // then read read second and so on

}

您可以嘗試使用掃描儀和計數器:

     ArrayList<Double> array = new ArrayList<Double>();
     Scanner input = new Scanner(new File("numbers.txt"));
     int counter = 0;
     while(input.hasNextLine() && counter < 10)
     {
         array.add(Double.parseDouble(input.nextLine()));
         counter++;
     }

只要文件中有更多輸入,這應該循環10行,並將每行添加到arraylist。

ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
    System.err.println(ex.toString());
    //here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
    //read line by line with the readLine() method
    while ((line = reader.readLine()) != null && counter < N) { 
    //check also the counter if it is smaller then desired amount of lines to read
        array.add(line); //add the line to the ArrayList of strings
        counter++; //update the counter of the read lines (increment by one)
    }
    //the while loop will exit if:
    // there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
    // OR the desired amount of line was correctly read
    reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
    System.err.println(ex.toString());
}

請參閱此如何使用Java逐行讀取大文本文件?

我認為這會起作用:

BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    int i = 0;
    while ((line = br.readLine()) != null)
    {
        if (i < 5)
        {
            // process the line.
            i++;
        }
    }
    br.close();
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
        new InputStreamReader(new FileInputStream("numbers.txt")))) {
    for (int i = 0; i < 5; ++i) { // Loops 5 times
        String line = in.readLine();
        if (line == null) [ // End of file?
            break;
        }
        // line does not contain line-ending.
        int num = Integer.parseInt(line);
        array.add(i);
    }
} // Closes in.
System.out.println(array);
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
    myList.add(fileScanner.nextDouble());
}

確保文件中包含“ numberOfLinesToRead”行。

  BufferedReader br = new BufferedReader(new FileReader(file));
  List<String> nlines = IntStream.range(0, hlines)
    .mapToObj(i -> readLine(br)).collect(Collectors.toList());

  String readLine(BufferedReader reader) { 
    try { 
      return reader.readLine();
    } catch (IOException e) { 
      throw new UncheckedIOException(e);
    }
  } 

您可以執行以下操作:

try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
    List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
    // do something with the list here
}

作為JUnit測試的完整示例:

public class ReadFirstLinesOfFileTest {

    @Test
    public void shouldReadFirstTenNumbers() throws Exception {
        Path p = Paths.get("numbers.txt");
        Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());

        try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
            List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
            List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
            Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM