首页 > 解决方案 > 在批量上传期间关闭流的最佳方法

问题描述

我正在通过 Box Java API 将批量文件(比如 50000)上传到 Box。为此,我们调用了 uploadFile 方法 50000 次。该方法还创建和关闭文件输入流。

有没有办法在批量加载完成之前保持流打开?即使我在 finally 块中关闭流,每次调用该方法时它都会关闭它。

private static String uploadFile(String pathFileName, BoxAPIConnection api, BoxFolder folder) {
    boolean fileExists = false;
    String fileId = null;
    FileInputStream stream = null;
    log.debug("Invoked uploadFileAsBoxAppUser-uploadFile :" + pathFileName + ":" + api + ":" + folder);
    try {
        String fileName = pathFileName.substring(pathFileName.lastIndexOf("\\") + 1, pathFileName.length());
        log.debug("fileName :" + fileName);

        for (BoxItem.Info itemInfo : folder) {
            if (itemInfo instanceof BoxFile.Info) {
                BoxFile.Info fileInfo = (BoxFile.Info) itemInfo;
                if (fileName.equals(fileInfo.getName())) {
                    fileExists = true;
                    fileId = fileInfo.getID();
                    log.debug("fileExists in Destination box Folder fileID " + fileId);
                }
            }
        }

        if (!fileExists) {
            log.debug("uploading new file: " + fileName);
            stream = new FileInputStream(pathFileName);
            BoxFile.Info boxInfo = folder.uploadFile(stream, pathFileName);
            fileId = boxInfo.getID();
        } else {
            log.debug("uploading new version of file: " + fileName);
            BoxFile file = new BoxFile(api, fileId);
            stream = new FileInputStream(pathFileName);
            file.uploadVersion(stream);
        }
    } catch (IOException e) {
        log.debug("Exception in uploadFileAsBoxAppUser :" + e);
    }
    finally {
        if (stream != null)
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    return fileId;
}

标签: javajava-iobox-api

解决方案


推荐阅读