Here you can find the source of formatCpfCNPJ(String str)
public static String formatCpfCNPJ(String str)
//package com.java2s; //License from project: Open Source License import java.text.ParseException; import javax.swing.text.MaskFormatter; public class Main { public static String formatCpfCNPJ(String str) { str = str.replaceAll("[\\D]", ""); String pattern;//from w w w . j a v a 2s . c o m if (str.length() <= 11) { str = String.format("%011d", Long.parseLong(str)); pattern = "###.###.###-##"; } else { str = String.format("%014d", Long.parseLong(str)); pattern = "##.###.###/####-##"; } try { MaskFormatter mask = new MaskFormatter(pattern); mask.setValueContainsLiteralCharacters(false); return mask.valueToString(str); } catch (ParseException e) { throw new RuntimeException(e); } } }