Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

How can I pull a random line from a text file in java?

I want to pull a random line from a text file rather than use inputFile.nextLine());

1 Answer

Relevance
  • 3 years ago

    A computer always reads a file sequentially. Even if you tell it to read from the end, it is actually scanning from the beginning to the end under the hood.

    If you want to choose a random line from a text file, you will need to read in all the lines and store them in a data structure. For example you can make a String[] array where each element is a line you read from the file. Then you can generate a random array index to choose a random line.

Still have questions? Get your answers by asking now.