Разделение и объединение PST‑файлов

API Aspose.Email предоставляет возможность разбить один PST‑файл на несколько PST‑файлов заданного размера. Он также может объединять несколько PST‑файлов в один. Операции разделения и объединения PST можно отслеживать, добавляя события к этим операциям.

Разделение и объединение PST‑файлов

Следующие образцы кода демонстрируют, как разбить большой PST‑файл на несколько небольших частей.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

PersonalStorage pst = PersonalStorage.fromFile(dataDir + "source.pst");
try {
    pst.StorageProcessed.add(new StorageProcessedEventHandler() {
        public void invoke(Object sender, StorageProcessedEventArgs e) {
            System.out.println("*** The chunk is processed: " + e.getFileName());
        }
    });

    pst.ItemMoved.add(new ItemMovedEventHandler() {
        public void invoke(Object sender, ItemMovedEventArgs e) {
            System.out.println("Moved to " + e.getDestinationFolder().retrieveFullPath());
        }
    });

    // Split the source PST into chunks of roughly 530 KB each
    pst.splitInto(542720, dataDir + "chunks/");
} finally {
    pst.dispose();
}

Объединение нескольких PST‑файлов в один PST

Следующий пример кода показывает, как объединить несколько PST‑файлов в один большой PST‑файл.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

// The PST files that will be merged into source.pst
String mergeWithFolderPath = dataDir + "MergeWith";

PersonalStorage pst = PersonalStorage.fromFile(dataDir + "source.pst");
try {
    pst.StorageProcessed.add(new StorageProcessedEventHandler() {
        public void invoke(Object sender, StorageProcessedEventArgs e) {
            System.out.println("*** The storage is merging: " + e.getFileName());
        }
    });

    pst.ItemMoved.add(new ItemMovedEventHandler() {
        public void invoke(Object sender, ItemMovedEventArgs e) {
            System.out.println("Moved to " + e.getDestinationFolder().retrieveFullPath());
        }
    });

    // Collect every PST file in the directory
    List<String> results = new ArrayList<String>();
    File[] files = new File(mergeWithFolderPath).listFiles();

    // listFiles() returns null if the path does not denote a directory
    if (files != null) {
        for (File file : files) {
            if (file.isFile() && file.getName().endsWith(".pst")) {
                results.add(file.getAbsolutePath());
            }
        }

        pst.mergeWith(results.toArray(new String[0]));
    }
} finally {
    pst.dispose();
}

Объединить папки из другого PST

API Aspose.Email позволяет объединять целые папки из другого PST в целевой PST, что приводит к получению PST большого размера.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

PersonalStorage destinationPst = PersonalStorage.fromFile(dataDir + "destination.pst");
try {
    PersonalStorage sourcePst = PersonalStorage.fromFile(dataDir + "source.pst");
    try {
        FolderInfo destFolder = destinationPst.getRootFolder().addSubFolder("FolderFromOtherPst");
        FolderInfo sourceFolder = sourcePst.getPredefinedFolder(StandardIpmFolder.Inbox);

        final int[] totalAdded = { 0 };
        destFolder.ItemMoved.add(new ItemMovedEventHandler() {
            public void invoke(Object sender, ItemMovedEventArgs e) {
                totalAdded[0]++;
            }
        });

        destFolder.mergeWith(sourceFolder);

        System.out.println("Total messages added: " + totalAdded[0]);
    } finally {
        sourcePst.dispose();
    }
} finally {
    destinationPst.dispose();
}

Разделить PST по заданному критерию

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

java.util.Calendar c = java.util.Calendar.getInstance();

// splitInto takes the library's own generic list, not java.util.List
com.aspose.email.system.collections.generic.List<MailQuery> criteria =
        new com.aspose.email.system.collections.generic.List<MailQuery>();

// Define a criterion based on the sent date
PersonalStorageQueryBuilder pstQueryBuilder = new PersonalStorageQueryBuilder();
c.set(2015, java.util.Calendar.JANUARY, 1, 0, 0, 0);
pstQueryBuilder.getSentDate().since(c.getTime());
c.set(2015, java.util.Calendar.DECEMBER, 12, 0, 0, 0);
pstQueryBuilder.getSentDate().before(c.getTime());
criteria.addItem(pstQueryBuilder.getQuery());

// Specify another criterion as well
pstQueryBuilder = new PersonalStorageQueryBuilder();
c.set(2012, java.util.Calendar.JANUARY, 1, 0, 0, 0);
pstQueryBuilder.getSentDate().since(c.getTime());
c.set(2012, java.util.Calendar.DECEMBER, 12, 0, 0, 0);
pstQueryBuilder.getSentDate().before(c.getTime());
criteria.addItem(pstQueryBuilder.getQuery());

PersonalStorage pst = PersonalStorage.fromFile(dataDir + "source.pst");
try {
    pst.splitInto(criteria, dataDir);
} finally {
    pst.dispose();
}

Отслеживание прогресса разбиения или объединения

Обе операции генерируют события во время выполнения, и приведённые выше примеры привязывают обработчик к каждому из них:

Обработчик — это анонимный StorageProcessedEventHandler или ItemMovedEventHandler добавлен с add(). Чтобы подсчитать перемещённые сообщения, храните счётчик в поле или в массиве из одного элемента, как делает пример объединения, поскольку локальная переменная, захваченная анонимным классом, должна быть эффективно final.