首页 » 技术分享 » 解析VCARD文件(vcf格式)导入QQ通讯录功能

解析VCARD文件(vcf格式)导入QQ通讯录功能

 

参考了这篇文章:

http://www.blogjava.net/sundc/archive/2008/08/04/219877.html

http://www.blogjava.net/sundc/archive/2008/08/04/219863.html

页面上传一个从QQ邮箱导出的vcard文件,格式如下:

BEGIN:VCARD
VERSION:3.0
EMAIL;TYPE=HOME,INTERNET,pref:marketing@cache-cache.com.cn
FN:Cache Cache玩趣时尚
N:;Cache Cache玩趣时尚;;;
UID:7CBFDD99-8928-3646-86AE-1913A57F3B18
END:VCARD
BEGIN:VCARD
VERSION:3.0
EMAIL;TYPE=HOME,INTERNET,pref:hello@creativemarketmail.com
FN:Creative Market
N:;Creative Market;;;
UID:ACD17D48-3036-9C4F-8A51-039897733752
END:VCARD

在网上看了一些关于导出Android通讯录的例子,也是vcf格式的文件,但是格式不太一样,是类似这样的:

BEGIN:VCARD
VERSION:2.1
N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E5=BC=A0=E4=B8=89;;
FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E5=BC=A0=E4=B8=89
TEL;VOICE;PREF:1-370-000-0000
PHOTO;ENCODING=BASE64;PNG:iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAIAAABt+uBvAAAA。。。。
END:VCARD

我在最上头放的那个链接就是解析这个格式vcf文件的。不过原理都是一样,使用正则表达式分组嘛~~感谢那位博主大大~~

我是需要这个文件里的email和name就可以了。就是FN和EMAIL这两个字段。

	/**
	 * 把VCF文件解析成bean对象
     * 导入联系人
     * @param in
     * @throws SystemException 
     */
    public List<Contact>  importVCFFileContact(InputStream in) throws SystemException{
    	List<Contact> list = new ArrayList<Contact>();
        
         try {
             BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
                Document document = new DocumentImpl();
                BufferedWriter writer = null;

                String line;
                StringBuffer bu=new StringBuffer();
                while ((line = nextLine(reader)) != null) {
                    bu.append(line+"\r\n");
                }
                Pattern p=Pattern.compile("BEGIN:VCARD(\\r\\n)([\\s\\S\\r\\n\\.]*?)END:VCARD");//分组,
                Matcher m=p.matcher(bu.toString());
                while(m.find()){
                	Contact c = new Contact();
                	c.setUserId(FrameworkContextUtils.getCurrentUserId());
                	c.setStatus(Contact.STATUS_WAIT_INVITE);
                    String str=m.group(0);
                 
                     //姓名
                     String name="";
                     Pattern p1=Pattern.compile("FN:.*");//分组,
                     Matcher m1=p1.matcher(str);
                     while(m1.find()){
                    	 name=m1.group(0).substring(m1.group(0).indexOf("FN:")+"FN:".length());
                     }
                     c.setName(name);
                     
                     //email
                    String email="";
                    
//                    //直接找与email格式匹配的内容。但是若email格式中有中横线-,找不到。大家可以改改正则表达式~
//                    Pattern p2=Pattern.compile("\\w+(\\.\\w+)*@\\w+(\\.\\w+)+");//分组,
//                    Matcher m2=p2.matcher(str);
//                    while(m2.find()){
//                        email=m2.group(0);
//                    }
                    if (StringUtils.isBlank(email)) {
                    	 Pattern p3=Pattern.compile("EMAIL:.*");//分组,
                    	 Matcher m3=p3.matcher(str);
                         while(m3.find()){
                             email=m3.group(0).substring(m3.group(0).indexOf("EMAIL:")+"EMAIL:".length());
                         }
					}
                    if (StringUtils.isBlank(email)) {
                    	 Pattern p4=Pattern.compile("EMAIL;TYPE=HOME,INTERNET,pref:.*");//分组,
                   	 Matcher m4=p4.matcher(str);
                        while(m4.find()){
                            email=m4.group(0).substring(m4.group(0).indexOf("EMAIL;TYPE=HOME,INTERNET,pref:")+"EMAIL;TYPE=HOME,INTERNET,pref:".length());
                        }
					}
                    c.setEmail(email);
                    
                    list.add(c);
                 }
                 reader.close();
        } catch (Exception e) {
        	LOGGER.debug(e.getMessage());
            throw new SystemException("文件格式读取有错,请检查文件");
        } 
        return list;
        
    }
	
	/**
	 * 获取文件的内容
	 * 以下是源码中自代的方法
	 * @param reader
	 * @return
	 * @throws IOException
	 */
	 public static String nextLine(BufferedReader reader) throws IOException {
	        
        String line;
        String nextLine;
        
        do {
            line = reader.readLine();
            if (line == null) return null;
        } while (line.length() == 0);
        
        // Evolution style line folding
        while (line.endsWith("=")) {
            line = line.substring(0, line.length() - 1);
            line += reader.readLine();
            }
        // RFC 2425 line folding
        reader.mark(1000);
        nextLine = reader.readLine();
        if ((nextLine != null) 
            && (nextLine.length() > 0)
            && ((nextLine.charAt(0) == 0x20) // white space
                || (nextLine.charAt(0) == 0x09))) { // tab
            line += nextLine.substring(1);
        } else {
            reader.reset();
        }
        
        line = line.trim();
        return line;
    }

注意inputstream转为reader的时候的utf-8哦,不加可能会乱码。

	@RequestMapping(value = "vcardUpload")
	public String vcardUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User)request.getSession().getAttribute(SecurityConstants.SESSION_USER);
		request.setAttribute("user", user);
		
		UploadFile uploadFile = FileUpDownUtils.getUploadFile(request, "uploadVCF");
		String fileName = uploadFile.getFileName();
		File fi = uploadFile.getFile();
		InputStream inputStream = new FileInputStream(fi);
		String message =  "";
        if(inputStream.available()>2097152){
        	message =  "文件太大";
        }
        if(fileName==null){
        	message =  "文件错误";
        }
        int index1 = fileName.lastIndexOf(".");
        int index2 = fileName.length();
        String fileExt = fileName.substring(index1,index2);
        if (fileExt.toLowerCase().equals(".vcf")){
            try {
                List<Contact> contacts = friendsManager.importVCFFileContact(inputStream);
                if(contacts==null||contacts.size()==0){
                	message =  "导入记录0条,可能是导入文件内容格式不正确";
                } else {
                	Contact temp = null;
					for (Contact contact : contacts) {
						temp = contactManager.getByUserIdAndEmail(FrameworkContextUtils.getCurrentUserId(), contact.getEmail());
						if (temp == null) {
							contactManager.save(contact);
						} else {
							message += "邮件地址为:  " + contact.getEmail() + "  的用户已存在。";
						}
						
					}
					message = "导入成功." + message;
				}
            } catch (Exception e) {
            	message =  "文件格式发生错误";
            }    
        } else{
        	message =  "不是vcf文件";
        }
        System.out.println(message);
		return "redirect:/member/friends/contact/all";
	}

导入成功:

转载自原文链接, 如需删除请联系管理员。

原文链接:解析VCARD文件(vcf格式)导入QQ通讯录功能,转载请注明来源!

0