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

Java 如何从文本文件中只读取一个内容?,java,Java,我可以从文件中读取,并且可以通过更改for循环中的数字来更改给定的行数,但我不希望文件中的所有数字都像那样并排显示。我需要他们一个一个地随机倒下 public class Assignment2 { public static void main(String[] args) throws IOException { // Read in the file into a list of strings BufferedReader reader

我可以从文件中读取,并且可以通过更改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);
        }
    }
}
公共类分配2{
公共静态void main(字符串[]args)引发IOException
{
//将文件读入字符串列表
BufferedReader=new BufferedReader(new FileReader(“textfile.txt”);
列表行=新的ArrayList();
字符串行=reader.readLine();
while(行!=null){
行。添加(行);
line=reader.readLine();
}
//从列表中随机选择一个
随机r=新随机();

对于(int p=0;p我认为您想要打印的是

String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);
仅显示此列表中的前20个随机行(可能是100行)

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

   int rowNum = r.nextInt(lines.size ());
   System.out.println(lines.get(rowNum);
}
for(int i=0;i<20;i++){
int rowNum=r.nextInt(lines.size());
System.out.println(lines.get(rowNum));
}

请更清楚地解释您的意思。输出是并排的所有数字,然后生成我分配的多少列。我需要将数字随机向下移动,直到有20列。我的txt文件是20'输入'10'输入'15,依此类推。现在我如何才能做到只读取文本文件中的数字量?对不起我对这个LPT有点陌生:学会更清晰地沟通。你是什么意思?我的for是不是在错误的位置?我试着从100个数字中只读入20个随机数字谢谢,我很感激,很抱歉一开始无法理解我,所以我又被卡住了。我如何将这20个数字打印出来,而不是打印出来,如何将它们放入输入文件?尝试了一些事情