java 操作ftp服务器
package easy.ftpService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class Ftp {
private String Control_Encoding = "UTF-8";
private FTPClient client = null;
private String host = "";
private int port = 21;
private String user = "";
private String password = "";
private String ftpPath = "/";
private String configFile = "ftpconfig";
private String ftpName;
private ResourceBundle property = null;
@SuppressWarnings("unused")
private Ftp() {
}
public Ftp(String host, int port, String user, String pwd) {
this.host = host;
this.port = port;
this.user = user;
this.password = pwd;
}
public Ftp(String ftpName) {
this.ftpName = ftpName;
setArg(configFile);
}
private void setArg(String configFile) {
try {
property = ResourceBundle.getBundle(configFile);
user = property.getString(ftpName + "username");
password = property.getString(ftpName + "password");
host = property.getString(ftpName + "host");
port = Integer.parseInt(property.getString(ftpName + "port"));
} catch (Exception e) {
System.out.println("配置文件 " + configFile + " 无法读取!");
}
}
public String getHome() {
return this.ftpPath;
}
public static final String ANONYMOUS_USER = "anonymous";
public void connect() throws Exception {
if (client == null) {
client = new FTPClient();
}
if (client.isConnected()) {
return;
}
client.setControlEncoding(Control_Encoding);
try {
client.connect(this.host, this.port);
if (this.user == null || "".equals(this.user)) {
client.login(ANONYMOUS_USER, ANONYMOUS_USER);
} else {
client.login(this.user, this.password);
}
client.setFileType(FTPClient.BINARY_FILE_TYPE);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
throw new Exception("connection FTP fail!");
}
FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);
config.setServerLanguageCode("zh");
client.configure(config);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
} catch (IOException e) {
throw new Exception("connection FTP fail! " + e);
}
}
public void close() {
if (client != null && client.isConnected()) {
try {
client.logout();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public List<FTPFile> list() {
List<FTPFile> list = null;
try {
FTPFile ff[] = client.listFiles(ftpPath);
if (ff != null && ff.length > 0) {
list = new ArrayList<FTPFile>(ff.length);
Collections.addAll(list, ff);
} else {
list = new ArrayList<FTPFile>(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public void switchDirectory(String path, boolean forcedIncrease) {
try {
if (path != null && !"".equals(path)) {
boolean ok = client.changeWorkingDirectory(path);
if (ok) {
this.ftpPath = path;
} else if (forcedIncrease) {
StringTokenizer token = new StringTokenizer(path, "\\//");
while (token.hasMoreTokens()) {
String npath = token.nextToken();
client.makeDirectory(npath);
client.changeWorkingDirectory(npath);
if (ok) {
this.ftpPath = path;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void createDirectory(String path) {
try {
if (path != null && !"".equals(path)) {
boolean ok = client.changeWorkingDirectory(path);
if (!ok) {
StringTokenizer token = new StringTokenizer(path, "\\//");
while (token.hasMoreTokens()) {
String npath = token.nextToken();
client.makeDirectory(npath);
client.changeWorkingDirectory(npath);
}
}
}
client.changeWorkingDirectory(this.ftpPath);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean deleteDirectory(String path) {
boolean flag = false;
try {
flag = client.removeDirectory(path);
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public boolean deleteFile(String path) {
boolean flag = false;
try {
flag = client.deleteFile(path);
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public boolean upload(File localFile) {
return this.upload(localFile, "");
}
public boolean upload(File localFile, String reName) {
boolean flag = false;
String targetName = reName;
if (reName == null || "".equals(reName)) {
targetName = localFile.getName();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(localFile);
client.setControlEncoding(Control_Encoding);
client.setFileType(FTPClient.BINARY_FILE_TYPE);
boolean ok = client.storeFile(targetName, fis);
if (ok) {
flag = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public boolean download(String ftpFileName, String savePath) {
boolean flag = false;
File dir = new File(savePath);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = null;
try {
String saveFile = dir.getAbsolutePath() + File.separator + ftpFileName;
fos = new FileOutputStream(new File(saveFile));
boolean ok = client.retrieveFile(ftpFileName, fos);
if (ok) {
flag = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public static void main(String args[]) {
Ftp ftp = new Ftp("ATTATEST_");
try {
ftp.connect();
System.out.println("当前位置:" + ftp.getHome());
ftp.switchDirectory("/test", true);
System.out.println("当前位置:" + ftp.getHome());
List<FTPFile> list = ftp.list();
System.out.println("|-- " + ftp.getHome());
for (FTPFile f : list) {
System.out.println(" |-- [" + (f.getType() == 0 ? "文件" : "文件夹") + "]" + f.getName());
}
boolean r1 = ftp.upload(new File("D:\\FTPLocalService\\沃尔沃若.docx"), "测试文件2.txt");
System.out.println("上传文件:" + r1);
boolean r2 = ftp.download("沃尔沃若.docx", "C:\\Users\\Administrator\\Desktop");
System.out.println("下载文件:" + r2);
boolean r3 = ftp.deleteFile("/test/测试文件2.txt");
System.out.println("删除文件:" + r3);
boolean r4 = ftp.deleteDirectory("/test");
System.out.println("删除目录:" + r4);
} catch (Exception e) {
e.printStackTrace();
}
ftp.close();
}
}
#FTP配置文件
#============Attachment============#
ATTACHMENT_username=1
ATTACHMENT_password=1
ATTACHMENT_host=1
ATTACHMENT_port=1
ATTATEST_username=bank
ATTATEST_password=bank@2019
ATTATEST_host=182.43.136.119
ATTATEST_port=56321
pom
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>