FTP文件上传及下载
1.FTP的连接及登录
publicstaticFtpClient connectFTP(String url,intport, String username, String password) {
//创建ftp
FtpClient ftp =null;
try{
//创建地址
SocketAddress addr =newInetSocketAddress(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();
}
returnftp;
}
2.上传文件到FTP服务器
publicstaticvoidupload(String localFile, String ftpFile, FtpClient ftp) {
OutputStream os =null;
FileInputStream fis =null;
try{
// 将ftp文件加入输出流中。输出到ftp上
os = ftp.putFileStream(ftpFile);
File file =newFile(localFile);
// 创建一个缓冲区
fis =newFileInputStream(file);
byte[] bytes =newbyte[1024];
intc;
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服务器下载文件
publicstaticvoiddownload(String localFile, String ftpFile, FtpClient ftp) {
InputStream is =null;
FileOutputStream fos =null;
try{
// 获取ftp上的文件
is = ftp.getFileStream(ftpFile);
File file =newFile(localFile);
byte[] bytes =newbyte[1024];
inti;
fos =newFileOutputStream(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();
}
}
}
备注:(1)ftp上传下载需要在平台配置,
(2)下载文件空格转变成+处理方式:FileDownLoad.downloadFile(ftpFileData, response, URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+","%20"));