如何从文本文件中只读取一个内容?

时间:2016-02-10 04:31:34

标签: java

我可以从文件读入,并且能够通过更改for循环中的数字来更改给定的行数,但我不希望我的文件中的所有数字并排显示。我需要他们一个接一个地随便下去。

public class Assignment2 {

    public static void main(String[] args) throws IOException 
    {
        // Read in the file into a list of strings
        BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
        List<String> lines = new ArrayList<String>();

        String line = reader.readLine();

        while( line != null ) {
            lines.add(line);
            line = reader.readLine();
        }

        // Choose a random one from the list
        Random r = new Random();

        for (int p = 0; p<3; p++)
        {
            String randomString = lines.get(r.nextInt(2));
            System.out.println(lines);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您要打印的是

class Life {
 public:
  Life(int age) : person_(new Person(age)) {}
  ...

仅显示此列表中可能为100的前20个随机行

String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);