0
Random access line from the file..
hii gus.. i want to access random data from the. file so can any one tell me..how to achieve it.. and. also send the syntax for demonstration.. i was trying to solve it.throw many website but at last a.i not able.. so plz frnd tell me how to write the code for it.. thanks in advance
10 Answers
+ 12
Use LinkedHashMap or your HashMap won't keep the order in which you put the values in it.
// Instantiation
LinkedHashMap map = new LinkedHashMap();
// Put an element to the map
map.put(new Integer(0), "firstLineOfFile");
// Print elements of the map
Set set = map.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + " " +
me.getValue());
}
+ 11
You have to replace the string in my example by the line you read from the file (BufferedReader, readLine method). And of course increment the keys. I recommend a while loop surrounding the map.put statement.
while(bufferedReader.readLine!=null) will be true as long there are lines.
Putting it all together provides you the entire code.
If you have further problems, publish your code at the playground, then I will help you bugfixing.
+ 10
You will need to read the whole file to a collection, which is accessible by a key and can store a String, e.g. a LinkedHashMap. Use an int key. Then use Math.random() to access a random value in the range of the first key to the last key.
+ 10
Another solution but you need to know exactly how many lines the file contains:
// rand can be defined by Math.random(), for
// the range you need the number of
// lines in your files.
String line = Files.readAllLines(Paths.get("file.txt")).get(rand)
+ 10
Then extend LinkedHashMap and overwrite the toString method. You can return any string you want from that.
+ 2
can u tell me..how to add the file in the collection..actually i am already using hashmap..
+ 1
thank u Tashi N.
i m going to check it..after short period,i will respond.
+ 1
hey..i want to put an eternal file in this..so how can do it.
+ 1
okay thank a lot tashi
0
yes..i did like this..but problem is there that..
the print statement also show the key with value.