8
URL url =  new URL("ftp://user:pass@ftp.example.com/thefolder/");
URLConnection connection = url.openConnection();
...
// List files in folder...

使用类似上面的方法,我想知道如何获取文件夹“thefolder”中的文件列表?


继这个原始问题之后,我整理了这个简单的 FTP 连接,它一切正常且看起来不错。它可以看到 /live/conf/ 位置中的所有文件,并将它们全部复制到本地 /conf/ 位置。

唯一的问题是,它正在复制文件但没有内容。它们都是 0KB 并且是空的。

任何人都可以看到任何明显的复制文件名而不是文件内容的东西吗?

try {
    FTPClient ftp = new FTPClient();
    ftp.connect("000.000.000.000");
    ftp.login("USER", "PASSWORD");
    ftp.enterLocalPassiveMode();
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    FTPFile[] files = ftp.listFiles("/live/conf/");
    for (int i=0; i < files.length; i++) {
        if (files[i].getName().contains(".csv")) {

            String remoteFile1 = files[i].getName();
            File downloadFile1 = new File("/var/local/import/conf/"+files[i].getName());
            OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
            ftp.retrieveFile(remoteFile1, outputStream1);
            outputStream1.close();                  

        }
    }
    ftp.disconnect();
} catch (SocketException ex) {
    ex.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
}   
4

3 回答 3

9

Java SEURLConnection不适合从 FTP 主机检索文件列表的工作。至于 FTP,它基本上只支持 FTPgetput命令(检索或上传文件)。它不支持ls您基本上正在寻找的 FTP 命令(列出文件),更不用说其他许多命令了。

您需要寻找支持 FTPls命令(以及更多)的第 3 方库。一个常用的是Apache Commons Net FtpClient。在其javadoc中演示了如何发出ls

FTPClient f = new FTPClient();
f.connect(server);
f.login(username, password);
FTPFile[] files = f.listFiles(directory);
于 2013-01-07T16:46:29.207 回答
5

你可以使用Apache commons FTPClient

这将允许您调用 listFiles...

public static void main(String[] args) throws IOException {
        FTPClient client = new FTPClient();
        client.connect("c64.rulez.org");
        client.enterLocalPassiveMode();
        client.login("anonymous", "");
        FTPFile[] files = client.listFiles("/pub");
        for (FTPFile file : files) {
            System.out.println(file.getName());
        }
于 2013-01-07T16:45:48.660 回答
2

看看我找到的这个类。它为你做起重。 在 nsftools.com 上课

示例是:

FTPConnection ftpConnect = new FTPConnection();
ftpConnect.connect("ftp.example.com");
ftpConnect.login("user","pass");

System.out.println(ftpConnect.listFiles());
于 2013-01-07T16:42:39.307 回答