首先架设一个FTP服务器,随便使用什么服务器都行:
然后去ftp://ftp.ntu.edu.tw/Apache/commons/net/下载commons net包和ftp包。导入到您的java工程,之后代码如下:
- 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 fis = null;
- try {
- ftpClient.connect("您的ip");
- ftpClient.login("您的ftp用户名", "密码");
- File srcFile = new File("C://ftp.txt");
- fis = new FileInputStream(srcFile);
- //设置上传目录
- ftpClient.changeWorkingDirectory("/ftproot");
- ftpClient.setBufferSize(1024);
- ftpClient.setControlEncoding("GBK");
- //设置文件类型(二进制)
- ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- ftpClient.storeFile("hello.txt", fis);
- } catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("FTP客户端出错!", e);
- } finally {
- IOUtils.closeQuietly(fis);
- try {
- ftpClient.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("关闭FTP连接发生异常!", e);
- }
- }
- }
- /**
- * FTP下载单个文件测试
- */
- public static void testDownload() {
- FTPClient ftpClient = new FTPClient();
- FileOutputStream fos = null;
- try {
- ftpClient.connect("您的ip");
- ftpClient.login("您的ftp用户名", "密码");
- String remoteFileName = "/ftproot/hello.txt";
- fos = new FileOutputStream("c:/hello.txt");
- ftpClient.setBufferSize(1024);
- //设置文件类型(二进制)
- ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- ftpClient.retrieveFile(remoteFileName, fos);
- } catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("FTP客户端出错!", e);
- } finally {
- IOUtils.closeQuietly(fos);
- try {
- ftpClient.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("关闭FTP连接发生异常!", e);
- }
- }
- }
- }