67,513
社区成员
发帖
与我相关
我的任务
分享
public static void downFile() {
// ftp登录用户名
String userName = "ssas";
String userPassword = "sasasa";
// ftp地址:直接IP地址
String server = "119.16.39.92";
// ftp端口
int port = 6888;
// 指定读取的目录
String path = "scas";
// 指定本地写入文件
String localPath="D:\\ftp\\";
FTPClient ftp = new FTPClient();
try {
int reply;
//1.连接服务器
ftp.connect(server,port);
//2.登录服务器 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(userName, userPassword);
//3.判断登陆是否成功
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
System.out.println(ftp.getStatus());
//4.指定要下载的目录
boolean falg= ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录
System.out.println(falg);
//5.遍历下载的目录
// String[] names = ftp.listNames();
System.out.println(ftp.getStatus(path));
FTPFile[] fs = ftp.listFiles();
System.out.println("文件数量:" + fs.length);
for (FTPFile ff : fs) {
//解决中文乱码问题,两次解码
byte[] bytes=ff.getName().getBytes("iso-8859-1");
String fn=new String(bytes,"utf8");
//6.写操作,将其写入到本地文件中
File localFile = new File(localPath + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}