所需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);
}
}
}
}
本文介绍如何使用Java进行FTP文件上传和下载操作。通过commons-net库中的FTPClient类,演示了如何连接到FTP服务器、登录、切换工作目录、设置文件类型,并完成文件的上传和下载过程。
1万+

被折叠的 条评论
为什么被折叠?



