在 Java 中使用 vCard(VCF)文件

本文覆盖了 VCardContact 类,独立于 Outlook 和 MAPI 读取和写入 vCard(VCF)文件。用于创建和管理 Outlook MapiContact 项目 — 也可以导出为 VCF — 参见 使用 Outlook 联系人.

VCardContact 与 MapiContact

Aspose.Email 通过两个不同的类公开联系人,选择正确的类可避免大量混淆:

  • VCardContact — 一个纯 vCard 对象。使用它当源和目标都是 vCard(VCF)文件且不需要 Outlook/MAPI 功能时。它直接读取和写入 VCF,支持 vCard 2.1/3.0/4.0 以及每文件多个联系人。
  • MapiContact — 一个 Outlook 联系人。使用它在处理 MSG/PST 或需要 MAPI 特定属性时。 MapiContact 也可以通过其 fromVCard 和 save 方法(参见 使用 Outlook 联系人).

本文其余部分侧重于 VCardContact.

创建 vCard 并保存

该 VCardContact 类具有无参数构造函数,并公开诸如 VCardIdentificationInfo, VCardOrganization, VCardEmailCollection, VCardTelephoneNumberCollection,以及 VCardDeliveryAddressCollection.

以下代码片段展示了如何从头构建联系人并将其保存为 vCard(VCF)文件。

VCardContact contact = new VCardContact();

VCardFullName fullName = new VCardFullName();
fullName.setGivenName("Bertha");
fullName.setMiddleName("A.");
fullName.setFamilyName("Buell");

VCardIdentificationInfo identificationInfo = new VCardIdentificationInfo();
identificationInfo.setDisplayName("Bertha Buell");
identificationInfo.setFullName(fullName);
identificationInfo.setNickname("Bertie");
identificationInfo.setBirthday(new GregorianCalendar(1980, java.util.Calendar.MAY, 20).getTime());
contact.setIdentificationInfo(identificationInfo);

VCardOrganization organization = new VCardOrganization();
organization.setOrganization("Awthentikz");
organization.setTitle("Social work assistant");
contact.setOrganization(organization);

VCardEmail email = new VCardEmail();
email.setEmailAddress("BerthaABuell@example.com");
email.setEmailType(VCardEmailType.INTERNET);
contact.getEmails().addItem(email);

// Save as a vCard (VCF) file
contact.save("contact.vcf");

联系人属性模型

除了上述的姓名和电子邮件之外,一个 VCardContact 通过强类型属性集公开完整的 vCard 数据模型。下面的代码片段扩展了 contact 之前创建的。

邮政地址

邮政地址位于 VCardDeliveryAddressCollection as VCardDeliveryAddress 项目。地址类型接受组合的 VCardDeliveryAddressType 标志(HOME, WORK, POSTAL, PARCEL, DOM, INTL, PREF).

VCardContact contact = new VCardContact();

VCardDeliveryAddress address = new VCardDeliveryAddress();
address.setAddressType(VCardDeliveryAddressType.WORK | VCardDeliveryAddressType.PREF);
address.setStreet("4 Darwinia Loop");
address.setLocality("Eighty Mile Beach");
address.setRegion("WA");
address.setPostalCode("6725");
address.setCountryName("Australia");

contact.getDeliveryAddresses().addItem(address);

电话号码

电话号码位于 VCardTelephoneNumberCollection as VCardTelephoneNumber 项目。电话类型采用组合 VCardTelephoneType 标志(VOICE, WORK, HOME, CELL, FAX, PAGER, PREF,以及更多)。

VCardContact contact = new VCardContact();

VCardTelephoneNumber workPhone = new VCardTelephoneNumber();
workPhone.setTelephoneNumber("(08) 9080 1183");
workPhone.setTelephoneType(VCardTelephoneType.WORK | VCardTelephoneType.VOICE);

VCardTelephoneNumber mobilePhone = new VCardTelephoneNumber();
mobilePhone.setTelephoneNumber("(925) 599 3355");
mobilePhone.setTelephoneType(VCardTelephoneType.CELL);

contact.getTelephoneNumbers().addItem(workPhone);
contact.getTelephoneNumbers().addItem(mobilePhone);

地理位置

该 Geo 属性将全局位置存储为 float 纬度和经度。

VCardContact contact = new VCardContact();

VCardGeo geo = new VCardGeo();
geo.setLatitude(48.858844f);
geo.setLongitude(2.294351f);

contact.setGeo(geo);

照片

联系人照片设置在 IdentificationInfo.Photo 作为 VCardPhoto。它可以通过图像字节内嵌或通过 URL 引用。图像格式由 VCardPhotoType 以及存储模式通过 VCardValueLocation.

VCardContact contact = new VCardContact();
contact.setIdentificationInfo(new VCardIdentificationInfo());

// Embed the image bytes inline
VCardPhoto inlinePhoto = new VCardPhoto();
inlinePhoto.setData(Files.readAllBytes(Paths.get("portrait.jpg")));
inlinePhoto.setPhotoType(VCardPhotoType.JPEG);
inlinePhoto.setValueLocation(VCardValueLocation.INLINE);
contact.getIdentificationInfo().setPhoto(inlinePhoto);

// Or reference an external image by URL
VCardPhoto linkedPhoto = new VCardPhoto();
linkedPhoto.setUri("https://example.com/portrait.jpg");
linkedPhoto.setPhotoType(VCardPhotoType.JPEG);
linkedPhoto.setValueLocation(VCardValueLocation.URL);
contact.getIdentificationInfo().setPhoto(linkedPhoto);

格式化地址标签

标签是已格式化、可直接打印的收件地址文本。标签位于 VCardLabelCollection as VCardLabel 项目,每个都标记了地址类型。

VCardContact contact = VCardContact.load("contact.vcf");

for (VCardLabel label : contact.getLabels()) {
    System.out.println(label.getAddressType());
    System.out.println(label.getAddress());
}

读取模型返回

加载 vCard 后,相同的属性集会公开解析后的数据。

VCardContact loaded = VCardContact.load("contact.vcf");

if (loaded.getIdentificationInfo() != null) {
    System.out.println(loaded.getIdentificationInfo().getDisplayName());
}

for (VCardDeliveryAddress address : loaded.getDeliveryAddresses()) {
    System.out.println(address.getAddressType() + ": " + address.getStreet() + ", " + address.getLocality());
}

for (VCardTelephoneNumber phone : loaded.getTelephoneNumbers()) {
    System.out.println(phone.getTelephoneType() + ": " + phone.getTelephoneNumber());
}

if (loaded.getGeo() != null) {
    System.out.println("Geo: " + loaded.getGeo().getLatitude() + ", " + loaded.getGeo().getLongitude());
}

安全性(公钥或证书)

该 VCardSecurity 属性公开存储在 vCard 中的公钥或身份验证证书( KEY 属性)。它的 saveToPEM 方法将该密钥写入 PEM 文件。

VCardContact signed = VCardContact.load("signed.vcf");

if (signed.getSecurity() != null && signed.getSecurity().getKey() != null) {
    System.out.println("Key type: " + signed.getSecurity().getType());

    // Export the embedded public key / certificate to a PEM file
    signed.getSecurity().saveToPEM("public-key.pem");
}

加载 vCard

使用静态 VCardContact.load 方法从文件或流读取 vCard。加载后,联系人的属性可通过创建时使用的相同属性集访问。

// Load from a file
VCardContact contact = VCardContact.load("contact.vcf");
System.out.println(contact.getIdentificationInfo().getDisplayName());

// Load from a stream
try (InputStream stream = Files.newInputStream(Paths.get("contact.vcf"))) {
    VCardContact fromStream = VCardContact.load(stream);
    System.out.println(fromStream.getIdentificationInfo().getDisplayName());
}

使用特定编码加载

要控制读取时使用的文本编码,请传入 VCardLoadOptions 对象并设置其首选编码。

VCardLoadOptions loadOptions = new VCardLoadOptions();
loadOptions.setPreferredEncoding(StandardCharsets.UTF_8);

VCardContact contact = VCardContact.load("contact.vcf", loadOptions);

从单个文件读取多个联系人

一个 vCard 文件可能包含多个联系人。使用静态 isMultiContacts 方法以检查文件或流是否包含多个联系人,以及 loadAsMultiple 将它们全部读取到一个 List<VCardContact>。两种方法都有文件、流和加载选项的重载:

  • static boolean isMultiContacts(String filePath) / isMultiContacts(InputStream stream)
  • static List<VCardContact> loadAsMultiple(String filePath) / loadAsMultiple(String filePath, VCardLoadOptions options)
  • static List<VCardContact> loadAsMultiple(InputStream stream) / loadAsMultiple(InputStream stream, VCardLoadOptions options)
try (InputStream stream = Files.newInputStream(Paths.get("contacts.vcf"))) {
    if (VCardContact.isMultiContacts(stream)) {
        List<VCardContact> contacts = VCardContact.loadAsMultiple(stream);

        for (VCardContact contact : contacts) {
            System.out.println(contact.getIdentificationInfo().getDisplayName());
        }
    }
}

保存选项

该 VCardSaveOptions 类自定义联系人写入方式:

  • Version —— 从中输出的 vCard 版本 VCardVersion 枚举: V21 (vCard 2.1,默认), V30 (3.0),或 V40 (4.0)。
  • PreferredTextEncoding —— 写入文件时使用的编码。
  • UseExtensions —— 是否扩展(X-) 可以写入属性。默认是 true.
  • ProductId —— 写入的值到 PRODID 属性。
VCardContact contact = VCardContact.load("contact.vcf");

VCardSaveOptions saveOptions = new VCardSaveOptions();
saveOptions.setVersion(VCardVersion.V30);                    // write vCard 3.0 (the default is V21)
saveOptions.setPreferredTextEncoding(StandardCharsets.UTF_8); // encoding used when writing
saveOptions.setUseExtensions(true);                          // allow extended (X-) properties
saveOptions.setProductId("My Company");                      // PRODID value

contact.save("contact_v3.vcf", saveOptions);

也可以将版本直接传递给构造函数:

VCardContact contact = VCardContact.load("contact.vcf");
contact.save("contact_v4.vcf", new VCardSaveOptions(VCardVersion.V40));

另见