FTPClient的jar包下载地址:
http://commons.apache.org/proper/commons-net/download_net.cgi
在commons-net-3.6.jar里面
文件上传:
在commons-net-3.6.jar里面
文件上传:
public static void main(String[] args) {
ftpUpload("223.105.1.100", "cmsoftu****", "syzw****", "E:\\recordfilecopy\\record1.txt", "/home/cmsoftu/detail/", "record1.txt");
}
public static void ftpUpload(String url, String username, String password, String localfilepath, String serverpath, String filename) {
FTPClient ftpClient = new FTPClient();
// 创建ftp连接。默认是21端口
try {
ftpClient.connect(url, 21);
ftpClient.login(username, password);
// 读取本地文件
FileInputStream inputStream = new FileInputStream(new File(localfilepath));
// 设置上传的路径
ftpClient.changeWorkingDirectory(serverpath);
// 修改上传文件的格式
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 第一个参数:服务器端文档名(即上传到服务器上的文件名)
// 第二个参数:上传文档的inputStream
ftpClient.storeFile(filename, inputStream);
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
}
文件下载:
public static void main(String[] args) {
ftpDownloadFile("223.105.1.100", "cmsoftu****", "syzw****", "E:\\recordfile", "/home/cmsoftu/detailcopy", "record1.txt");
}
public static boolean ftpDownloadFile(String url, String username, String password, String localPath, String remotePath, String fileName) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, 21);
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}