使用JSch

时间:2017-04-05 17:43:05

标签: java sftp jsch

我需要在SFTP文件夹中获取文件名的递归列表。现在我使用以下代码:

private void getFilesRecursive(List<LsEntry> fileList, List<FileDto> response, String dirParentName,
        SftpManagerWithPool manager) throws SftpException {
    for (LsEntry file : fileList) {
        if (!file.getAttrs().isDir()) {
            response.add(new FileDto(file.getFilename(), StorageType.FOLDER.getName(),
                    new Attributes(file.getAttrs().getATime(), file.getAttrs().getMTime(),
                            file.getAttrs().getAtimeString(), file.getAttrs().getMtimeString(),
                            file.getAttrs().getPermissionsString(), getPathWitoutRootDirectoryt(dirParentName),
                            file.getAttrs().getSize(), file.getAttrs().isDir())));
        } else if (file.getAttrs().isDir() && !".".equals(file.getFilename())) {
            List<LsEntry> files = manager.listFiles(context.getBasePath().concat("/")
                    .concat(dirParentName.concat("/").concat(file.getFilename())));
            getFilesRecursive(files, response, dirParentName.concat("/").concat(file.getFilename()), manager);
        }
    }
}

public List<FileDto> getFiles() throws ServiceException {
    Session session = null;
    SftpManagerWithPool manager = null;
    try {
        session = getSession();
        manager = new SftpManagerWithPool(session);
        manager.connect();
        List<FileDto> response = new ArrayList<>();
        List<LsEntry> files = manager
                .listFiles(context.getBasePath().concat("/").concat(context.getPathToProcess()));
        getFilesRecursive(files, response, context.getPathToProcess(), manager);
        return response;
    } catch (Exception e) {
        throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(),
                e.getLocalizedMessage());
    } finally {
        if (manager != null) {
            manager.disconnect();
            try {
                returnSession(session);
            } catch (Exception e) {
                throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(),
                        e.getLocalizedMessage());
            }
        }
    }
}

以下是SftpManagerWithPool中的方法:

@SuppressWarnings("unchecked")
public List<LsEntry> listFiles(String pathFrom) throws SftpException {
    if (c == null || session == null || !session.isConnected() || !c.isConnected()) {
        throw new SftpException(ErrorCode.LIST_FILES.ordinal(), "Connection to server is closed. Open it first.");
    }
    String filePath = pathFrom + "/";
    return c.ls(filePath);
}

一切都运行良好,不超过5k文件,但是当我们有更多文件时,需要花费大量时间并导致超时。

我的问题是,如何使用c.ls(filePath);方法仅列出文件夹中的前N个文件?我正在寻找类似于Linux shell命令ls -U | head -4

的东西

---- ----- EDIT

我修改了我的方法listFiles如下,但我仍然没有获得更好的表现:

public List<LsEntry> listFiles(String pathFrom, int top) throws SftpException {
        if (c == null || session == null || !session.isConnected() || !c.isConnected()) {
            throw new SftpException(ErrorCode.LIST_FILES.ordinal(), "Connection to server is closed. Open it first.");
        }
        String filePath = pathFrom + "/";
        List<LsEntry> response = new ArrayList<>();
        c.ls(filePath, new LsEntrySelector() {

            @Override
            public int select(LsEntry record) {
                if (response.size() <= top) {
                    response.add(record);
                    return LsEntrySelector.CONTINUE;
                } else {
                    return LsEntrySelector.BREAK;
                }
            }
        });
        return response;
    }

非常感谢你:)

1 个答案:

答案 0 :(得分:2)

使用overload of ChannelSftp.ls method that takes LsEntrySelector interface

public void ls(String path, LsEntrySelector selector)

实施LsEntrySelector.select以收集文件条目。一旦你有足够的,让它返回BREAK