读取损坏的 PST/OST 文件

读取损坏的 PST/OST 文件

有时由于某些问题可能无法读取 PST/OST。例如,某些数据块可能已损坏。在这种情况下,调用时通常会抛出异常 EnumerateFolders, EnumerateMessages, GetContents, GetSubfolders,等方法。但存储中的单个邮件或文件夹可能仍保持完好。

Aspose.Email 用户可以层次化地查找项目标识符。此外,还可以通过标识符提取项目。为此,库提供了以下方法:

注意,尽管有这些优势,仍有损坏的存储即使使用这些方法也无法读取。

以下代码片段演示了使用这些方法读取损坏的 PST/OST 文件:

try (PersonalStorage pst = PersonalStorage.fromFile(fileName)) {
    exploreCorruptedPst(pst, pst.getRootFolder().getEntryIdString());
}

public static void exploreCorruptedPst(PersonalStorage pst, String rootFolderId) {
    Iterable<String> messageIdList = pst.findMessages(rootFolderId);

    for (String messageId : messageIdList) {
        try {
            MapiMessage msg = pst.extractMessage(messageId);
            System.out.println("- " + msg.getSubject());
        } catch (Exception e) {
            System.out.println("Message reading error. Entry id: " + messageId);
        }
    }

    Iterable<String> folderIdList = pst.findSubfolders(rootFolderId);

    for (String subFolderId : folderIdList) {
        if (subFolderId != rootFolderId) {
            try {
                FolderInfo subfolder = pst.getFolderById(subFolderId);
                System.out.println(subfolder.getDisplayName());
            } catch (Exception e) {
                System.out.println("Message reading error. Entry id: " + subFolderId);
            }

            exploreCorruptedPst(pst, subFolderId);
        }
    }
}

从损坏的文件中提取 PST 项目

遍历 API 允许尽可能提取所有 PST 项目,即使原始文件的某些数据已损坏,也不会抛出异常。

使用 PersonalStorage(TraversalExceptionsCallback callback) 构造函数和 load(String fileName) 方法而不是 fromFile 方法。

构造函数允许定义回调方法。

TraversalExceptionsCallback exceptionsCallback = new TraversalExceptionsCallback() {
    @Override
    public void invoke(TraversalAsposeException exception, String itemId) {
        /* Exception handling  code. */
    }
};

try (PersonalStorage pst = new PersonalStorage(exceptionsCallback)) { }

加载和遍历期间的异常将通过回调方法提供。

如果文件加载成功且可以继续遍历,load 方法返回 ’true’;如果文件已损坏且无法遍历,则返回 ‘false’。

if (currentPst.load(inputStream))

以下代码示例展示了如何在项目中实现 PST 文件遍历 API:

public static void main(String[] args) {
    TraversalExceptionsCallback exceptionsCallback = new TraversalExceptionsCallback() {
        @Override
        public void invoke(TraversalAsposeException exception, String itemId) {
            /* Exception handling  code. */
        }
    };

    try (PersonalStorage pst = new PersonalStorage(exceptionsCallback)) {
        if (pst.load("test.pst")) {
            getAllMessages(pst, pst.getRootFolder());
        }
    }
}

private static void getAllMessages(PersonalStorage pst, FolderInfo folder) {
    for (String messageEntryId : folder.enumerateMessagesEntryId()) {
        MapiMessage message = pst.extractMessage(messageEntryId);
    }
    for (FolderInfo subFolder : folder.getSubFolders()) {
        getAllMessages(pst, subFolder);
    }
}