Ubuntu20.04 搭建 FTP 服务,java上传、下载和删除
1、前言
ftp搭建需求
2、安装
sudo apt-get remove vsftpd
sudo rm /etc/pam.d/vsftpd
sudo apt-get install vsftpd
3、ftp配置
sudo vim /etc/vsftpd.conf
anonymous_enable=YES
write_enable=YES
anon_upload_enable=YES
anon_world_readable_only=NO
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list
utf8_filesystem=YES
local_root=/home/ftp
seccomp_sandbox=NO
sudo vim /etc/vsftpd.chroot_list
root
bjlthy
ftp
3、添加用户
sudo groupadd ftp
sudo useradd ftp
sudo passwd ftp
sudo adduser ftp ftp
cat /etc/passwd
4、给文件夹权限,开发端口
cd /home/
sudo mkdir ftp
sudo chgrp ftp /home/ftp -R #给ftp文件夹指定用户
sudo chown ftp /home/ftp -R #给ftp文件夹指定用户
sudo chmod -R 777 /home/ftp
sudo apt-get install iptables
sudo iptables -I INPUT -p tcp --dport 21 -j ACCEPT
sudo iptables-save
sudo /etc/init.d/vsftpd restart
ps -ef | grep ftp
vsftpd 530 Login incorrect
sudo vim /etc/shells
/sbin/nologin #添加
5、java代码
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
package com.ruoyi.project.utils;
import java.io.*;
import ch.qos.logback.classic.Logger;
import com.ruoyi.project.tool.tcc.LogbackUtil;
import org.apache.commons.net.ftp.*;
public class FtpUtil {
private Logger logger = LogbackUtil.getLogger("FtpUtil");
private FTPClient ftpClient;
public static void main(String[] args) throws Exception {
FtpUtil ftpUtil = new FtpUtil();
FtpModel ftpModel = ftpUtil.getFtpModel("192.168.1.177", 21, "ftp", "123456");
String connect = ftpUtil.connect(ftpModel);
System.out.println("======== connect " + connect);
String uploadFile = ftpUtil.uploadFile("./testDir", "C:\\Users\\A\\Desktop\\桌面临时\\FtpUtil.java");
System.out.println("uploadFile " + uploadFile);
// String downloadDir = ftpUtil.downloadDirFiles(ftpModel, "C:\\Users\\A\\Desktop\\桌面临时\\downloadDir", "./testDir");
// System.out.println("downloadDir " + downloadDir);
// String res = ftpUtil.downloadFile("./testDir/FtpUtil.java", "C:\\Users\\A\\Desktop\\桌面临时\\ftpSave", "FtpUtil222.java");
// System.out.println("======== res " + res);
// String deleteFile = ftpUtil.deleteFile("./testDir", "FtpUtil.java");
// System.out.println("======== deleteFile " + deleteFile);
}
public String connect(FtpModel ftpModel) {
ftpClient = new FTPClient();
String res;
try {
ftpClient.connect(ftpModel.getIp(), ftpModel.getPort());
ftpClient.login(ftpModel.getUserName(), ftpModel.getPassword());
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("UTF-8");
// ftpClient.changeWorkingDirectory(ftpModel.getWorkDir());
ftpClient.enterLocalPassiveMode();
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
res = "-1 " + reply;
} else {
res = "0 " + reply;
}
} catch (Exception e) {
logger.error("连接ftp服务失败" + e.getMessage(), e);
e.printStackTrace();
res = "-1 " + e.getMessage();
}
return res;
}
public String uploadFile(String remoteBaseDir, String fileName) throws Exception {
try {
boolean makeDirectory = ftpClient.makeDirectory(remoteBaseDir);
boolean b1 = ftpClient.changeWorkingDirectory(remoteBaseDir);
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
boolean b = ftpClient.storeFile(file.getName(), fileInputStream);
fileInputStream.close();
return b ? "0" : "-1";
} catch (Exception e) {
e.printStackTrace();
return "-1 " + e.getMessage();
}
}
public String downloadFile(String remoteFileName, String saveDir, String fileName) {
String res;
try {
File fileDir = new File(saveDir);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
File localFile = new File(saveDir + File.separatorChar + fileName);
OutputStream os = new FileOutputStream(localFile);
//ftp中文名需要iso-8859-1字符
boolean flag2 = ftpClient.retrieveFile(new String(remoteFileName.getBytes("GBK"), "iso-8859-1"), os);
os.close();
closeFtp();
if (!flag2) {
localFile.delete();
res = "-1 " + "没有找到 " + remoteFileName + " 该文件";
} else {
res = "0";
}
} catch (Exception e) {
e.printStackTrace();
res = "-1 " + e.getMessage();
}
return res;
}
public void closeFtp() {
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* ftp上传文件
*/
public void upload(File file) throws Exception {
if (!file.isDirectory()) {
FileInputStream fileInputStream = new FileInputStream(file);
ftpClient.storeFile(file.getName(), fileInputStream);
fileInputStream.close();
} else {
ftpClient.makeDirectory(file.getName());
ftpClient.changeWorkingDirectory(file.getName());
String[] files = file.list();
for (String fileStr : files) {
File file1 = new File(file.getPath() + "/" + fileStr);
if (file1.isDirectory()) {
upload(file1);
ftpClient.changeToParentDirectory();
} else {
File file2 = new File(file.getPath() + "/" + fileStr);
FileInputStream fileInputStream = new FileInputStream(file2);
ftpClient.storeFile(file2.getName(), fileInputStream);
fileInputStream.close();
}
}
}
}
public String downloadDirFiles(FtpModel ftpModel, String localBaseDir, String remoteBaseDir) {
String connect = connect(ftpModel);
if (connect.startsWith("-1")) {
return "-1 连接失败";
}
try {
FTPFile[] files;
boolean isChangeDir = ftpClient.changeWorkingDirectory(remoteBaseDir);
if (!isChangeDir) {
return "-1 changeWorkingDirectory fail";
}
ftpClient.setControlEncoding("UTF-8");
files = ftpClient.listFiles();
for (FTPFile ftpFile : files) {
downloadFile(ftpFile, localBaseDir);
// deleteFtpFile(remoteBaseDir, ftpFile.getName());
}
closeFtp();
return "0";
} catch (Exception e) {
e.printStackTrace();
return "-1 下载过程中出现异常" + e.getMessage();
}
}
private void downloadFile(FTPFile ftpFile, String localBaseDir) {
OutputStream outputStream;
try {
String localFilePath = localBaseDir + File.separatorChar + ftpFile.getName();
File locaFile = new File(localFilePath);
if (locaFile.exists()) {
return;
}
File fileParent = locaFile.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
outputStream = new FileOutputStream(localFilePath);
ftpClient.retrieveFile(ftpFile.getName(), outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
logger.error(e.toString());
e.printStackTrace();
}
}
public String deleteFile(String remoteDir, String remoteFileName) {
String res;
try {
ftpClient.changeWorkingDirectory(remoteDir);
int dele = ftpClient.dele(remoteFileName);
res = dele == 250 ? "0" : "-1";
} catch (Exception e) {
logger.error("删除的文件失败");
e.printStackTrace();
res = "-1 " + e.getMessage();
}
return res;
}
public FtpModel getFtpModel(String ip, Integer port, String userName, String password) {
return new FtpModel(ip, port, userName, password);
}
public class FtpModel {
public String ip;
public Integer port;
public String userName;
public String password;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public FtpModel() {
}
public FtpModel(String ip, Integer port, String userName, String password) {
this.ip = ip;
this.port = port;
this.userName = userName;
this.password = password;
}
}
}