这是我的代码:
String serverAddress = "ftp://ftp.nasdaqtrader.com/symboldirectory/"; // ftp server address
int port = 21; // ftp uses default port Number 21
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(serverAddress, port);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE/FTP.ASCII_FILE_TYPE);
String remoteFilePath = "/nasdaqtraded.txt";
File localfile = new File(System.getProperty("user.dir")+"\\src\\test\\resources\\stocks.txt");
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localfile));
boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
outputStream.close();
if (success) {
System.out.println("Ftp file successfully download.");
}
} catch (IOException ex) {
System.out.println("Error occurs in downloading files from ftp Server : " + ex.getMessage());
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
我正在从本地主机运行它,因此我可以从纳斯达克网站下载股票列表,问题是它给了我这个错误:
从ftp服务器下载文件时出错:ftp://ftp.nasdaqtrader.com/symboldirectory/:无效的IPv6地址
我了解这是因为我正在尝试从本地主机下载文件,是否有解决方法?
我正在尝试下载此文件: ftp://ftp.nasdaqtrader.com/symboldirectory/nasdaqtraded.txt
就是我的电脑。
答案 0 :(得分:2)
FTPClient
类的connect()
方法希望传递给要连接的服务器的主机名。
与从
SocketClient
派生的所有类一样,您必须先使用connect
连接到服务器,然后再进行任何操作,最后是在disconnect
与服务器完全交互之后,再进行连接。
但是,您的代码正在传递URI,该URI被误解为IPv6地址(可能是因为它包含冒号)。
您应该改为connect()
到服务器的主机名。
String hostname = "ftp.nasdaqtrader.com";
int port = 21;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(hostname, port);
答案 1 :(得分:-1)
我遇到了同样的问题,发现这很有帮助
Read a file from NASDAQ FTP Server
Maven依赖项:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Java代码:
FTPClient ftpClient = new FTPClient();
ftpClient.setStrictReplyParsing(false);
int portNumber = 21;
String pass = "anonymous";
try {
// connect to NASDAQ FTP
ftpClient.connect("ftp.nasdaqtrader.com", portNumber);
ftpClient.login(pass, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
if (ftpClient.isConnected()) {
log.debug("connection successful");
ftpClient.changeWorkingDirectory("/SymbolDirectory");
String remoteFile = "nasdaqlisted.txt";
InputStream in = new BufferedInputStream(ftpClient.retrieveFileStream(remoteFile));
String text = IOUtils.toString(in, StandardCharsets.UTF_8.name());
if(text != null) {
log.debug("write successful; \n {}", text);
}
}
ftpClient.logout();
} catch (IOException e) {
log.error("connection failed", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
log.error("failed to disconnect", e);
}
}