Bookmark Topic Watch Topic
  • New Topic

Collection to read data from a file and store it in memory???

 
Sneha Kashyap
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hi,

data in the file(will be read into a Set) (I am not exactly sure as to which collection to be used for this purpose) Please suggest the collection to be used.

abc def ghi
abc ghi
def ghi abc
uvw xyz
xyz abc
xyz def

How to read each line in this file and store it in a collection and also help me as to which collection can be used.
Please provide some sample code for the same
Thanks.
 
Swastik Dey
Rancher
Posts: 1602
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Report post to moderator
As far as reading is concerned you can have a look into java.io or java.util.Scanner, and as far storing in collection is concerned probably you won't be able to store it into hashmap or hashtable because as the sample data looks it doesn't seem to have any unique key, others should be fine and usage depends upon your requirement.
 
Sneha Kashyap
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hi thanks,

would be great if you could helpme with some sample code....
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Report post to moderator
This is essentially the same question as this one and this one, in both of which you've received several answers. If you have questions about those, please continue the discussion in one of those topics; I'm closing this one.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
Sneha Kashyap wrote:would be great if you could helpme with some sample code....

Here on JavaRanch we love to help people learn Java, but we don't want to give out complete solutions, because that doesn't help people learn Java.

Do you know how to read a file line by line? It's easy to do with a BufferedReader object, which has a readLine() method to read one line from a file. Write a loop that keeps calling readLine() until it returns null (which means you've reached the end of the file). Instead of BufferedReader you could also use class Scanner; you'd have to use the methods hasNextLine() and nextLine() from that class. Lookup the API documentation of those classes and try out how they work.

What collection you should use depends on what the purpose of the program is. If you just need to store all the lines, then a List (ArrayList or LinkedList) would be an obvious choice. But you're mentioning a Set in your question.
 
    Bookmark Topic Watch Topic
  • New Topic