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();
}
最佳答案
Java SE URLConnection
不适合从 FTP 主机检索文件列表的工作。至于FTP,它基本上只支持FTP get
或put
命令(检索或上传文件)。它不支持您基本上正在寻找的 FTP ls
命令(列出文件),更不用说许多其他命令了。
您需要寻找支持 FTP ls
命令(以及更多)的第 3 方库。一个常用的是 Apache Commons Net FtpClient
.在其javadoc演示了如何发出 ls
:
FTPClient f = new FTPClient();
f.connect(server);
f.login(username, password);
FTPFile[] files = f.listFiles(directory);
关于java - URLConnection FTP 列表文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14200106/