Java对接FTP服务器实现上传下载
- 相关推荐
概述
FTP是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。FTP作为网络共享文件的传输协议,在网络应用软件中具有广泛的应用。FTP的目标是提高文件的共享性和可靠高效地传送数据。在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)。本文就主要针对这两个操作来进行说明(当然,也包括FTP服务器的连接和登录等操作)。
环境搭建
系统环境:Windows 7(客户端与服务器均是)
服务器:自建FTP服务器(关于FTP服务器的搭建,本文不作说明。网上都有.)
开发环境:Jdk 1.8
引入第三方库:commons-net-2.2.jar(针对第一种方法)
一、基于第三方库FtpClient的FTP服务器数据传输
由于是基于第三方库,所以这里基本上没有太多要说明的东西。就是导入第三方库再调用即可,调用过程从下面的代码可以参见。为了便于文章的完整性,这也是给出其程序结构图吧。
FTP Client传输
1.FTP的连接及登录
public static FtpClient connectFTP(String url, int port, String username, String password) {
//创建ftp
FtpClient ftp = null;
try {
//创建地址
SocketAddress addr = new InetSocketAddress(url, port);
//连接
ftp = FtpClient.create();
ftp.connect(addr);
//登陆
ftp.login(username, password.toCharArray());
ftp.setBinaryType();
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
FTP上传
2.上传文件到FTP服务器
public static void upload(String localFile, String ftpFile, FtpClient ftp) {
OutputStream os = null;
FileInputStream fis = null;
try {
// 将ftp文件加入输出流中。输出到ftp上
os = ftp.putFileStream(ftpFile);
File file = new File(localFile);
// 创建一个缓冲区
fis = new FileInputStream(file);
byte[] bytes = new byte[1024];
int c;
while((c = fis.read(bytes)) != -1){
os.write(bytes, 0, c);
}
System.out.println("upload success!!");
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os!=null) {
os.close();
}
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.从FTP服务器下载文件
public static void download(String localFile, String ftpFile, FtpClient ftp) {
InputStream is = null;
FileOutputStream fos = null;
try {
// 获取ftp上的文件
is = ftp.getFileStream(ftpFile);
File file = new File(localFile);
byte[] bytes = new byte[1024];
int i;
fos = new FileOutputStream(file);
while((i = is.read(bytes)) != -1){
fos.write(bytes, 0, i);
}
System.out.println("download success!!");
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fos!=null) {
fos.close();
}
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FTP下载文件