Java for loop read file line by line

Description

Java for loop read file line by line


import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {
   public static void main(String[] args) throws Exception {
      List<String> fileList = new ArrayList<String>();
      BufferedReader reader = new BufferedReader(new FileReader("Main.java"));
      for (String line = reader.readLine(); line != null; line = reader.readLine()) {
         fileList.add(line);//  ww w  .  j  a v  a 2  s  .  c om
      }
      reader.close();

      Random random = new Random();
      for (int i = 0; i < 10; i++) {
         System.out.format("%d: %s%n", i, fileList.get(random.nextInt(fileList.size() - 1)));
      }
   }
}



PreviousNext

Related