jdk1.8,FtpClientUtil 上传、下载单个文件
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
import java.io.*;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpClientUtil {
private FTPClient ftp = new FTPClient();
private String server = "192.168.1.10";
private String username = "dev";
private String password = "123456";
/**
* 上传单个文件
*
* @param filename
* @param pathName
* @param remoteFileName
*/
public void upload(String filename, String pathName, String remoteFileName) {
// ftp.configure(config);
boolean error = false;
try {
int reply;
ftp.connect(server);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(pathName);
try (final InputStream input = new FileInputStream(filename)) {
ftp.storeFile(remoteFileName, input);
}
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
// transfer files
ftp.logout();
} catch (IOException e) {
error = true;
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
// do nothing
}
}
System.exit(error ? 1 : 0);
}
}
public void download(String filename, String pathName, String remoteFileName) {
// ftp.configure(config);
boolean error = false;
try {
int reply;
ftp.connect(server);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(pathName);
try (final OutputStream output = new FileOutputStream(filename)) {
ftp.retrieveFile(remoteFileName, output);
}
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
// transfer files
ftp.logout();
} catch (IOException e) {
error = true;
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
// do nothing
}
}
System.exit(error ? 1 : 0);
}
}
public static void main(String[] args) {
String fileName = "D:/a.png";
String pathName = "test";
String remoteFileName = "a1.png";
FtpClientUtil ftpc = new FtpClientUtil();
//将D:/a.png 上传到/test/a1.png
ftpc.upload(fileName, pathName, remoteFileName);
fileName="D:/a2.jpg";
//将/test/a1.png 下载到D:/a2.png
ftpc.download(fileName, pathName, remoteFileName);
}
}