Java通过FTP协议给Linux主机传送文件:
Linux 主机环境准备:(我们是准备用 root 用户登录 ftp 协议并传送文件)
[root@localhost ~]# yum install -y vsftpd
# 如果安装失败查看是否有 epel-release
# rpm -qa | grep epel
# 如果没有 epel-release
# yum install -y epel-release
# 再安装 vsftpd
[root@localhost ~]# vim /etc/vsftpd/user_list
...
root <== 注释掉
...
[root@localhost ~]# vim /etc/vsftpd/ftpusers
...
root <== 注释掉
...
[root@localhost ~]# systemctl enable vsftpd //允许开机自启
[root@localhost ~]# systemctl restart vsftpd //重启服务
[root@localhost ~]# setenforce 0 //关闭 SElinux,或者自己调整 SElinux 允许登录用户对上传目录的读写权限,这里不提。
[root@localhost ~]# systemctl stop firewalld //关闭防火墙,或者开放 21 端口,如果用的是 iptables 也是同样处理。
Java 程序:(调用的包为 ccommons-net-3.5.jar 已上传)
public class FTP {
private Integer port = null;
private String user = null;
private String ipaddr = null;
private String password = null;
private FTPClient ftp = null;
public FTP(String ipaddr, String user, String password, Integer port) {
this.ipaddr = ipaddr;
this.user = user;
this.password = password;
this.port = port;
}
//pwdto 是 Linux 主机你要上传文件的目录,pwdfrom 是你文件所在目录
public void FTPsendFile(String pwdto, String pwdfrom, String[] fileList) {
if (this.FTPStart()) {
for (int i = 0; i < fileList.length; i++) {
this.FTPFileUpload(pwdto + fileList[i], pwdfrom + fileList[i]);
}
}
this.FTPClose();
}
private boolean FTPStart() {
boolean ISsuccessed = false;
this.ftp = new FTPClient();
try {
this.ftp.connect(this.ipaddr, this.port); //链接
this.ftp.login(this.user, this.password); //登录
this.ftp.setFileType(FTPClient.BINARY_FILE_TYPE); //设置发送文件的格式
int reply = this.ftp.getReplyCode(); //目标主机的回应
if (FTPReply.isPositiveCompletion(reply)) {
ISsuccessed = true;
} else {
this.ftp.disconnect();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ISsuccessed;
}
private boolean FTPFileUpload(String targetName, String localFile) {
boolean ISsuccessed = false;
FileInputStream fin = null;
File file = new File(localFile);
try {
fin = new FileInputStream(file); //将文件做成字符流
if (this.ftp.storeFile(targetName, fin)) { //上传
ISsuccessed = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ISsuccessed;
}
private boolean FTPClose() {
boolean ISsuccessed = false;
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
ISsuccessed = true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return ISsuccessed;
}
}
调用实例:
FTP ftp = new FTP("10.10.90.110","root","123456", 21);
String [] fileLists={"file1","file2","file3"};
ftp.FTPsendFile("/home/", "/home/sendfile/",fileLists);