Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Random Line reading in text file

807588Apr 29 2007 — edited Apr 9 2009
I am trying to read a random line in a text file but every time i read it it reads first line of the file any one can help me what is the problem in the code is or provide me with a new code.

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
File file = new File("word.txt");
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try{
//Open the file for reading
RandomAccessFile raf = new RandomAccessFile(file, "r");

raf.seek(file.length()); //Seek to end of file

System.out.println("Read full line: " + raf.readLine());
//str2 is a String
str2 = str2 + raf.readLine();
System.out.println(""+str2);

raf.close();
System.out.println("Successfully");
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
my text file look like in this format

mind
hate
Abhor
Bigot
narrow
prejudiced
person
Counterfeit
fake
false
give
voting
rights
Hamper
hinder
obstruct
Kindle
to
start
fire
harmful
poisonous
lethal
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 7 2009
Added on Apr 29 2007
9 comments
2,349 views