import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* <p>
* Title: Adage_[子系统统名]_[模块名]
* </p>
* <p>
* Description: [ftp上传下载文件]
* </p>
*
* @author benDaoRong
* @version $Revision$ 2014-8-14
* @author (lastest modification by $Author$)
* @since 1.0
*/
public class FtpTest {
/**
* <p>
* Discription:[上传文件到ftp服务器]
* </p>
*
* @return
*/
public static boolean upload() {
String url = "10.1.50.111";
String username = "test";
String password = "test";
FTPClient client = new FTPClient();
try {
client.connect(url);
client.login(username, password);
int reply = client.getReplyCode();
System.out.println("reoktCode:" + reply);
//
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
return false;
}
client.changeWorkingDirectory("F:/FTPROOT");
// 上传文件
// FileInputStream fileInput = new FileInputStream("F:/Desktop/620.txt");
// System.out.println("文件上传中,请耐心等待!");
// client.storeFile(new String("620.txt".getBytes("UTF-8"), "iso-8859-1"), fileInput);
// System.out.println("文件上传完成");
// 在ftp服务器上新建一个文件,然后将输入流写入文件。
InputStream input = new ByteArrayInputStream("今天测试ftp很成功111".getBytes());
client.storeFile(new String("中文名2.txt".getBytes("UTF-8"), "iso-8859-1"), input);
input.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (client.isConnected()) {
try {
client.disconnect();
System.out.println("关闭ftp连接");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* <p>
* Discription:[从ftp服务器下载文件]
* </p>
*/
public static void download() {
String url = "10.1.50.111";
String username = "test";
String password = "test";
FTPClient client = new FTPClient();
try {
client.connect(url);
client.login(username, password);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
}
// 设置ftp根目录
client.changeWorkingDirectory("F:/FTPROOT");
// 下载文件
FTPFile[] files = client.listFiles();
if (files != null && files.length > 0) {
for (FTPFile file : files) {
String fileName = new String(file.getName().getBytes("iso-8859-1"), "UTF-8");
// 本地文件存放目录
String localName = System.currentTimeMillis() + "_" + fileName;
OutputStream out = new FileOutputStream(new File("F:/Desktop/" + localName));
client.retrieveFile(file.getName(), out);
out.close();
System.out.println("文件[" + fileName + "]下载成功");
}
}
client.logout();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (client.isConnected()) {
try {
client.disconnect();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
// upload();
download();
}
}
Java实现FTP上传和下载
最新推荐文章于 2023-07-09 14:32:51 发布