我如何只从文本文件中读取一个东西? [英] How can I read only one thing in from a textfile?

查看:83
本文介绍了我如何只从文本文件中读取一个东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can read in from the file and am able to change the amount of lines given by changing the number in the for loop but I don't want all the numbers in my file displayed side by side like that. I need them all going down one by one randomly.

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);
        }
    }
}


推荐答案

我认为你要打印的是

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

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

To display only the first 20 random lines from this list of maybe 100

for (int i = 0; i < 20; i++) {

   int rowNum = r.nextInt(lines.size ());
   System.out.println(lines.get(rowNum);
}

这篇关于我如何只从文本文件中读取一个东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆