Random access line from the file.. | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
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

14th Mar 2017, 6:55 PM
Pratul Tripathi
Pratul Tripathi - avatar
10 Réponses
+ 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()); }
14th Mar 2017, 7:45 PM
Tashi N
Tashi N - avatar
+ 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.
14th Mar 2017, 7:58 PM
Tashi N
Tashi N - avatar
+ 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.
14th Mar 2017, 7:28 PM
Tashi N
Tashi N - avatar
+ 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)
14th Mar 2017, 7:31 PM
Tashi N
Tashi N - avatar
+ 10
Then extend LinkedHashMap and overwrite the toString method. You can return any string you want from that.
14th Mar 2017, 7:34 PM
Tashi N
Tashi N - avatar
+ 2
can u tell me..how to add the file in the collection..actually i am already using hashmap..
14th Mar 2017, 7:34 PM
Pratul Tripathi
Pratul Tripathi - avatar
+ 1
thank u Tashi N. i m going to check it..after short period,i will respond.
14th Mar 2017, 7:47 PM
Pratul Tripathi
Pratul Tripathi - avatar
+ 1
hey..i want to put an eternal file in this..so how can do it.
14th Mar 2017, 7:50 PM
Pratul Tripathi
Pratul Tripathi - avatar
+ 1
okay thank a lot tashi
14th Mar 2017, 8:15 PM
Pratul Tripathi
Pratul Tripathi - avatar
0
yes..i did like this..but problem is there that.. the print statement also show the key with value.
14th Mar 2017, 7:33 PM
Pratul Tripathi
Pratul Tripathi - avatar