Home page of this blog

Thursday, September 30, 2010

Java code to parse a big contact.vcf file into multiple contact files

My old mobile is often crashing and restarting. I wanted to transfer my contacts from old mobile to new mobile, when I got a single Contact.vcf file from old mobile. This file contained all the contacts, but new mobile accepted only one contact from a .vcf file

I wrote the program now and transfered all my contacts, if someone maybe facing a similar problem,  ... so I just post the source code.

A single .vcf corresponds to a business card

Here is the program I wrote for my personal use to split a single big Contact.vcf to multiple contact files, here I used the contact name as the name of the new business card file. Thanks to java ... I did not spend much time on perl or python ...

import java.io.*;
import java.util.*;

public class splitter
{
 public static void main(String[] args) throws Exception
 {
  FileReader fin = new FileReader(args[0]);
  BufferedReader in = new BufferedReader(fin);

  LinkedList<String> contactNames = new LinkedList<String>();
  LinkedList<String> contactsList = new LinkedList<String>();

  StringBuffer contact = null;

  boolean hasName = false;

  for(String sLine = in.readLine(); sLine != null; sLine = in.readLine())
  {
   if(sLine.startsWith("BEGIN:"))
   {
    contact = new StringBuffer();
    hasName = false;
   }
   else if(sLine.startsWith("END:"))
   {
    contact.append(sLine + "\n");
    if(hasName)
    {
     contactsList.add(contact.toString());
    }
    contact = null;
    continue;
   }
   else if(sLine.startsWith("N:"))
   {
    String[] tokens = sLine.split(":");

    if(tokens.length == 2)
    {
     hasName = true;
     String[] names = tokens[1].split(";");

     if(names.length >= 1)
     {
      contactNames.add(((names.length >= 2)?names[1]:"") + "_" + names[0]);
     }
    }

   }

   contact.append(sLine + "\n");
  }

  in.close();
  fin.close();

  Iterator<String> it = contactsList.iterator();

  for(String contactName: contactNames)
  {
   System.out.println("ContactName:" + contactName);

   String sFileName = contactName.replaceAll(" ", "_");

   String sContact = it.next();
   System.out.println(sContact);

   FileWriter fw = new FileWriter(sFileName + ".vcf");
   PrintWriter out = new PrintWriter(fw, true);

   out.println(sContact);
   out.close();

   fw.close();

  }
  
 }
}

2 comments:

  1. Thank you very much, I want to use the data in single vcf file and create XML file with the same data. This code will help me a lot and i will inform you about my progress

    ReplyDelete
  2. Brilliant - helped me out.
    Thanks.
    S

    ReplyDelete