import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public void ftpServer2Server() throws SocketException, IOException { FTPClient ftp1 = new FTPClient(); FTPClient ftp2 = new FTPClient(); //连接ftp ftp1.connect("xxx.xxx.xxx.xxx", 21); //可以不需要port ftp1.login("user", "123456"); //ftp2照样如此…… String initDir = "mydata"; ftp2.connect("xxx.com", 21); //可以不需要port ftp2.login("user2", "pswd2", initDir); ftp2.changeWorkingDirectory(initDir); //list files listFiles(ftp1); //list dir listFiles(ftp2); OutputStream os = ftp2.storeFileStream("testFromFtp.mp3");//这句话就是获取ftp2的流 if (os == null) { System.out.println(" italkdd.upload.akamai.com not open: " + ftp2.getReplyString()); return; } ftp1.retrieveFile("test.mp3", os); //这句话是把文件从ftp1复制到ftp2中,通过流is os.close(); System.out.println(" upload suc: " + ftp2.getReplyString()); // Must call completePendingCommand() to finish command. if (!ftp2.completePendingCommand()) {//完成数据传送,进入文件管理,这条语句特别关键,不然你不能进行文件管理操作(获取当前目录)特别重要 System.err.println("File transfer failed."); }else{ System.err.println("File transfer suc."); } /* InputStream input; OutputStream output; input = new FileInputStream("foobaz.txt"); output = ftp.storeFileStream("foobar.txt") if(!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) { input.close(); output.close(); ftp.logout(); ftp.disconnect(); System.err.println("File transfer failed."); System.exit(1); } Util.copyStream(input, output); input.close(); output.close(); // Must call completePendingCommand() to finish command. if(!ftp.completePendingCommand()) { ftp.logout(); ftp.disconnect(); System.err.println("File transfer failed."); System.exit(1); } */ listFiles(ftp2); ftp1.logout(); ftp1.disconnect(); ftp2.logout(); ftp2.disconnect(); } public void listFiles(FTPClient ftp) { //list dir try { FTPFile[] listfiles = ftp.listFiles(); for (int ii = 0; ii < listfiles.length; ii++) { System.out.println(" == " + listfiles[ii].getName()); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
用mvn,pom.xml中加入对apache commons的依赖:
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>