java 实现ftp上传如何创建文件夹?

如题所述

准备条件:java实现ftp上传用到了commons-net-3.3.jar包

首先建立ftphost连接

public boolean connect(String path, String addr, int port, String username, String password) {
try {
//FTPClient ftp = new FTPHTTPClient(addr, port, username, password);
ftp = new FTPClient();
int reply;
ftp.connect(addr);
System.out.println("连接到:" + addr + ":" + port);
System.out.print(ftp.getReplyString());
reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP目标服务器积极拒绝.");
System.exit(1);
return false;
}else{
ftp.login(username, password);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(path);
System.out.println("已连接:" + addr + ":" + port);
return true;
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
return false;
}
}

然后再利用ftpclient的makeDirectory方法创建文件夹

public void createDir(String dirname){
try{
ftp.makeDirectory(dirname);
System.out.println("在目标服务器上成功建立了文件夹: " + dirname);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}

断开host连接

public void disconnect(){
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

最后是程序的调用方法

public static void main(String[] args) {
FtpUploadTest ftpupload = new FtpUploadTest();
if(ftpupload.connect("", "172.39.8.x", 20, "administrator", "abc@123")){
ftpupload.createDir("/UPLOAD");
ftpupload.disconnect();
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-08-16

这个功能我也刚写完,不过我也是得益于同行,现在我也把自己的分享给大家,希望能对大家有所帮助,因为自己的项目不涉及到创建文件夹,也仅作分享,不喜勿喷谢谢!

interface :
package com.sunline.bank.ftputil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import org.apache.commons.net.ftp.FTPClient;

public interface IFtpUtils {
/**
  * ftp登录
  * @param hostname  主机名
  * @param port 端口号
  * @param username 用户名
  * @param password 密码
  * @return
  */
public  FTPClient loginFtp(String hostname,Integer port,String username,String password);
/**
  * 上穿文件
  * @param hostname 主机名
  * @param port 端口号
  * @param username 用户名
  * @param password 密码
  * @param fpath ftp路径
  * @param localpath  本地路径
  * @param fileName 文件名
  * @return
  */
public boolean uploadLocalFilesToFtp(String hostname,Integer port,String username,String password,String fpath,String localpath,String fileName);
/**
* 批量下载文件
* @param hostname
* @param port
* @param username
* @param password
* @param fpath
* @param localpath
* @param fileName 源文件名
* @param filenames 需要修改成的文件名
* @return
*/
public boolean downloadFileList(String hostname,Integer port,String username,String password,String fpath,String localpath,String fileName, String filenames);
/**
  * 修改文件名
  * @param localpath
  * @param fileName 源文件名
  * @param filenames 需要修改的文件名
  */
public void modifiedLocalFileName(String localpath,String fileName, String filenames);
/**
* 关闭流连接、ftp连接
* @param ftpClient
* @param bufferRead 
* @param buffer
*/
public void closeFtpConnection(FTPClient ftpClient,BufferedOutputStream bufferRead,BufferedInputStream buffer);
}

impl:
package com.sunline.bank.ftputil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import common.Logger;

public class FtpUtilsImpl implements IFtpUtils{
private static Logger log = Logger.getLogger(FtpUtilsImpl.class);
FTPClient ftpClient = null;
Integer reply = null;

@Override
public  FTPClient loginFtp(String hostname,Integer port,String username,String password) {
  ftpClient = new FTPClient();
try {
ftpClient.connect(hostname, port);
ftpClient.login(username, password);
ftpClient.setControlEncoding("utf-8");
reply = ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//设置文件类型为二进制(避免解压缩文件失败)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//开通数据端口传输数据,避免阻塞
ftpClient.enterLocalActiveMode();
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
log.error("连接FTP失败,用户名或密码错误");
}else{
log.info("FTP连接成功");
}
} catch (Exception e) {
if (!FTPReply.isPositiveCompletion(reply)) {
try {
ftpClient.disconnect();
} catch (IOException e1) {
log.error("登录FTP失败,请检查FTP相关配置信息是否正确",e1);
}
}
}
return ftpClient;
}

@Override
@SuppressWarnings("resource")
public boolean uploadLocalFilesToFtp(String hostname,Integer port,String username,String password,String fpath,String localpath,String fileName) {
boolean flag = false;
ftpClient = loginFtp(hostname, port, username, password);
BufferedInputStream buffer=null;
try {
buffer = new BufferedInputStream(new FileInputStream(localpath + fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName = new String(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if (!ftpClient.storeFile(fileName, buffer)) {
log.error("上传失败");
return flag;
}
buffer.close();
ftpClient.logout();
flag = true;
return flag;
} catch (Exception e) {
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient, null,buffer);
log.info("文件上传成功");
}
return false;
}

@Override
public boolean downloadFileList(String hostname,Integer port,String username,String password,String fpath,String localpath,String fileName, String filenames){
ftpClient = loginFtp(hostname, port, username, password);
boolean flag = false;
         BufferedOutputStream bufferRead=null;
if(fpath.startsWith("/") && fpath.endsWith("/")){
try {
//切换到当前目录
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile [] ftpFiles = this.ftpClient.listFiles();
for (FTPFile files : ftpFiles) {
if (files.isFile()) {
System.out.println("=================="+files.getName());
File localFile = new File(localpath + "/" + files.getName()); 
bufferRead = new BufferedOutputStream(new FileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(), bufferRead); 
bufferRead.flush();
}
}
ftpClient.logout();
flag = true;
               
} catch (IOException e) {
e.printStackTrace();
}finally{ 
            closeFtpConnection(ftpClient,bufferRead,null);
            log.info("文件下载成功");
         } 
}
modifiedLocalFileName(localpath,fileName,filenames);
return flag;
}

@Override
public void modifiedLocalFileName(String localpath,String fileName, String filenames){
File file = new File(localpath);
File [] fileList = file.listFiles();
if (file.exists()) {
if (null == fileList ||fileList.length == 0) {
log.error("文件夹是空的");
}else{
for (File data : fileList) {
String orprefix = data.getName().substring(0,data.getName().lastIndexOf("."));
String prefix = fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index===" + orprefix + "prefix ===" + prefix);
if (orprefix.contains(prefix)) {
boolean f = data.renameTo(new File(localpath + "/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,请检查。。。");
}
}
}
}
}
 

@Override
public void closeFtpConnection(FTPClient ftpClient,BufferedOutputStream bufferRead,BufferedInputStream buffer){
if(ftpClient.isConnected()){ 
             try{
                 ftpClient.disconnect();
             }catch(IOException e){
                 e.printStackTrace();
             }
         } 
if(null != bufferRead){
             try {
                 bufferRead.close();
             } catch (IOException e) {
                 e.printStackTrace();
             } 
         } 
if(null != buffer){
             try {
              buffer.close();
             } catch (IOException e) {
                 e.printStackTrace();
             } 
         } 
}
 
 
public static void main(String[] args) throws IOException {
String hostname = "xx.xxx.x.xxx";
Integer port = 21;
String username = "edwftp";
String password = "edwftp";
String fpath = "/etl/etldata/back/";
String localPath = "C:/Users/Administrator/Desktop/ftp下载/";
String fileName = "test.txt";
String filenames = "ok.txt";
FtpUtilsImpl ftp = new FtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname, port, username, password, fpath, localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname, port, username, password, fpath, localPath, fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}

第2个回答  推荐于2017-09-11
首先保证ftp服务器的创建文件夹权限已开放,关键代码如下。
/**
* 在当前目录下创建文件夹
*
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir) {
try {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); // sign
s.countTokens();
String pathName = ftpClient.pwd();
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}本回答被提问者采纳
第3个回答  2012-06-05
用ftp命令:mkdir()
可以创建文件夹。
第4个回答  2012-06-05
无法实现.服务器不能任由你修改.