Tweet
Tweet

Reputation: 678

read/write files in Java

How can I read a file easily in Java if I have following file format:

a|dip
a|dop
c|nap
a|dip
b|dop
b|sip
a|tang
c|dig
c|nap

I want to get all words that belongs to "a", "b", and "c". What data structure I can use to read and store this information?

You can also suggest some good file formats (two column) that is easy to read/write in Java.

I know some of you may be thinking that what is the real problem that I want to solve, I have some complex employee related data. Current (poor) system generate some files and I am trying to process them to add them in database. The current files' format is bit complex (private), I cannot copy past here.

Upvotes: 2

Views: 1579

Answers (3)

DaveMan
DaveMan

Reputation: 610

If you can use Google Guava (http://code.google.com/p/guava-libraries/) then you'll get a few handy classes (you can use some or all of these):

  1. com.google.common.io.Files
  2. com.google.common.io.LineProcessor<T>
  3. com.google.common.base.Charsets
  4. com.google.common.collect.Multimap<K,V>
  5. com.google.common.collect.ArrayListMultimap<K,V>

For example you could write:

LineProcessor<Multimap<String, String>> processor = 
    new LineProcessor<Multimap<String, String>>() {
      Multimap<String, String> processed = ArrayListMultimap.create();

      public boolean processLine(String line) {
        String parts[] = line.split("\\|", 2); // 2 keeps any | in the rest of the line
        processed.put(parts[0], parts[1]);
        return true; // keep going
      }

      public Multimap<String, String> getResult() {
        return processed;
      }
    };

Multimap<String, String> result = Files.readLines(
    new File("filename.txt"), Charsets.UTF_8, processor);

Upvotes: 6

Esko Luontola
Esko Luontola

Reputation: 73655

You can use Scanner to read the text file one line at a time and then you can use String.split("\\|") to separate the parts on that line. For storing the information, a Map<String,List<String>> might work.

Upvotes: 3

WhiteFang34
WhiteFang34

Reputation: 72079

I'd use this data structure:

Map<String, List<String>> map = new HashMap<String, List<String>>();

And parse the file like this:

File file = new File("words.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
    String next = scanner.next();
    String[] parts = next.split("\\|");
    String group = parts[0];
    String word = parts[1];

    List<String> list = map.get(group);
    if (list == null) {
        list = new ArrayList<String>();
        map.put(group, list);
    }
    list.add(word);
}

So you could get the list of words for "a" like so:

for (String word : map.get("a")) {
    System.out.println(word);
}

Upvotes: 0

Related Questions