Java 如何从文件中读取N行数?

Java 如何从文件中读取N行数?,java,for-loop,arraylist,bufferedreader,fileinputstream,Java,For Loop,Arraylist,Bufferedreader,Fileinputstream,我正在练习用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 ArrayL

我正在练习用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数组=新的ArrayList();
InputStream列表=新的BufferedInputStream(新文件InputStream(“numbers.txt”);

对于(双i=0;i您可以尝试使用扫描仪和计数器:

     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++;
     }
ArrayList数组=新的ArrayList();
扫描仪输入=新扫描仪(新文件(“numbers.txt”);
int计数器=0;
while(input.hasNextLine()&计数器<10)
{
add(Double.parseDouble(input.nextLine());
计数器++;
}
只要文件中有更多输入,就应该循环10行,将每行添加到arraylist。

arraylist array=new 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());
}
//字符串的ArrayList(因为您将读取字符串) BufferedReader reader=null; 试一试{ reader=new BufferedReader(new FileReader(“numbers.txt”);//读取文件 }catch(FileNotFoundException ex){//file numbers.txt不存在 System.err.println(例如toString()); //在这里,你应该停止你的程序,或者找到另一种方法来打开一些文件 } 字符串行;//存储读取行 int N=5;//要读取的最大行数 int counter=0;//当前已读取的行数 试一试{ //使用readLine()方法逐行读取 while((line=reader.readLine())!=null&&counter#行) //或者正确读取了所需的行数 reader.close();//关闭读取器和相关流 }catch(IOException ex){//如果存在输入/输出问题 System.err.println(例如toString()); }
List array=new ArrayList();
try(BufferedReader in=新的BufferedReader(
新的InputStreamReader(新文件InputStream(“numbers.txt”)){
对于(int i=0;i<5;++i){//循环5次
String line=in.readLine();
如果(line==null)[//文件结束?
打破
}
//行不包含行尾。
int num=Integer.parseInt(行);
数组。添加(i);
}
}//接近。
System.out.println(数组);
ArrayList myList=new ArrayList();
int numberOfLinesToRead=5;
文件f=新文件(“number.txt”);
Scanner fileScanner=新扫描仪(f);
对于(inti=0;i见下表

我认为这会奏效:

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();
BufferedReader br=new BufferedReader(new FileReader(file));
弦线;
int i=0;
而((line=br.readLine())!=null)
{
如果(i<5)
{
//处理生产线。
i++;
}
}
br.close();
BufferedReader br=new BufferedReader(new FileReader(file));
列表nlines=IntStream.range(0,hlines)
.mapToObj(i->readLine(br)).collect(Collectors.toList());
字符串读取行(BufferedReader读取器){
试试{
返回reader.readLine();
}捕获(IOE){
抛出新的未选中异常(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
}
try(BufferedReader=Files.newBufferedReader(path.get(“numbers.txt”)){
List first10Numbers=reader.lines().limit(10.collect)(Collectors.toList());
//对这里的列表做些什么
}
作为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());
        }
    }
}
public类ReadFirstLinesOfFileTest{
@试验
public void shouldReadFirstTennembers()引发异常{
Path p=Path.get(“numbers.txt”);
write(p,“0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n”.getBytes());
try(BufferedReader=Files.newBufferedReader(path.get(“numbers.txt”)){
List first10Numbers=reader.lines().limit(10.collect)(Collectors.toList());
所需列表=数组。asList(“0”、“1”、“2”、“3”、“4”、“5”、“6”、“7”、“8”、“9”);
Assert.assertArrayEquals(应为.toArray(),first10Numbers.toArray());
}
}
}

。谷歌搜索“如何用Java读取文件中的行”时返回的前10个结果回答了您的问题。谷歌有时会非常有用;)为什么要使用
ArrayList
?@LuiggiMendoza因为他的问题是阅读文本文件的N行,独立于文件本身的内容。我认为他画数字的事实只是为了给我们举个例子,我不这么认为。OP的意图非常明确。OP唯一无法实现的部分是阅读文本文件的内容文件。剩下的代码只是等待丢失的部分来解决这个难题。您也可以选择这样做。filter(line->line!=null)
  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
}
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());
        }
    }
}