Java에서 vCard(VCF) 파일 작업
이 문서는 VCardContact 클래스는 Outlook 및 MAPI와 무관하게 vCard(VCF) 파일을 읽고 씁니다. Outlook MapiContact 항목 — VCF로 내보낼 수도 있습니다 — 참조 Outlook 연락처 작업.
VCardContact vs MapiContact
Aspose.Email은 두 개의 서로 다른 클래스를 통해 연락처를 노출합니다. 올바른 클래스를 선택하면 많은 혼란을 피할 수 있습니다:
- VCardContact — 순수 vCard 객체입니다. 소스와 대상이 vCard(VCF) 파일이고 Outlook/MAPI 기능이 필요 없을 때 사용하십시오. VCF를 직접 읽고 쓰며, vCard 2.1/3.0/4.0 및 파일당 다중 연락처를 지원합니다.
- MapiContact — Outlook 연락처입니다. MSG/PST와 작업하거나 MAPI 전용 속성이 필요할 때 사용하십시오.
MapiContactVCF를 통해 가져오고 내보낼 수도 있습니다.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");
IdentificationInfo.FullName 문자열이며, Aspose.Email for Java에서는 VCardFullName 개별 이름/중간/성 부분을 가진 객체.
연락처 속성 모델
위에 표시된 이름과 이메일 외에도 VCardContact 전체 vCard 데이터 모델을 강력히 형식화된 속성 집합을 통해 노출합니다. 아래 스니펫은 contact 이전에 생성되었습니다.
우편 주소
우편 주소는 VCardDeliveryAddressCollection as VCardDeliveryAddress items. 주소 유형은 다음의 조합을 사용합니다 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());
}
VCardLabel 공개 생성자가 없으므로 라벨은 기존 vCard에서 읽으며 코드에서 구성되지 않습니다. 파일에 라벨을 기록하려면 직접 작성하는 경우, 다음을 채우십시오 VCardDeliveryAddress 필드 대신.
모델 다시 읽기
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());
}
}
}
isMultiContacts(InputStream) 스트림을 읽어 연락처 수를 감지합니다. 스트림을 다시 열거나(또는 파일 경로 오버로드를 사용) 호출하기 전에 loadAsMultiple 동일한 소스에서.
저장 옵션
다음은 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));
관련 항목
- Outlook 연락처 작업 — Outlook을 생성, 저장 및 읽기
MapiContact항목, VCF 가져오기 및 내보내기 포함. - PST 파일에서 연락처 작업 — PST 내부에 연락처를 저장하고 읽습니다.