所需jar包:commons-io-1.3.2.jar commons-net-3.0.1.jar
首先在自己的電腦上建立ftp伺服器,網上有很多軟體可以實現,我用的是quick easy ftp server
這裡伺服器的根目錄為:E:/myftp
package ftp;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
public class FtpTest
{
public static void main(String[] args)
{
testUpload();
testDownload();
}
/**
* FTP上傳單個檔案測試
*/
public static void testUpload()
{
FTPClient ftpClient = new FTPClient();
FileInputStream fin = null;
try
{
ftpClient.setDefaultPort(222);
ftpClient.connect("192.168.199.117");
if (!ftpClient.login("admin", "admin"))
{
System.out.print("login error !");
return;
}
//要上傳的檔案為touxiang.jpg
File srcFile = new File("E:/myftp/touxiang.jpg");
fin = new FileInputStream(srcFile);
//設定上傳目錄 這裡upload為根目錄的下一級檔案夾
ftpClient.changeWorkingDirectory("/upload");
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
//設定檔案類型(二進位)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//上傳上來的檔案儲存體為檔案名稱為upload.jpg的檔案
ftpClient.storeFile("upload.jpg", fin);
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("some ftp client error happened !", e);
}
finally
{
IOUtils.closeQuietly(fin);
try
{
ftpClient.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("failed to close ftp connection !", e);
}
}
}
/**
* FTP下載單個檔案測試
*/
public static void testDownload()
{
FTPClient ftpClient = new FTPClient();
FileOutputStream fos = null;
try
{
ftpClient.setDefaultPort(222);
ftpClient.connect("192.168.199.117");
if(!ftpClient.login("admin", "admin"))
{
System.out.print("login error !");
return;
}
String remoteFileName = "/touxiang.jpg";
fos = new FileOutputStream("E:myftp/download/down.jpg");
ftpClient.setBufferSize(1024);
//設定檔案類型(二進位)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFileName, fos);
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("some ftp client error happened !", e);
}
finally
{
IOUtils.closeQuietly(fos);
try
{
ftpClient.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("failed to close ftp connection !", e);
}
}
}
}