gpt4 book ai didi

java - 如何将目录上传到 FTP?

转载 作者:行者123 更新时间:2023-12-01 11:11:43 26 4
gpt4 key购买 nike

这是我的代码:

public void UploadIt(){
org.apache.commons.net.ftp.FTPClient con = null;

try
{
con = new FTPClient();
con.connect("ftp server");

if (con.login("username", "pass"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = baseDir + "/emre";

FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
Log.v(" dead","ddsd");
}

}

我可以上传文件,但无法上传目录。当我尝试上传目录或文件夹时,它显示“...是目录”,但无法上传。

最佳答案

在 ftp 上创建目录后,您必须从目录递归上传文件,因为在 ftp 上创建文件夹和创建文件不能同时完成,它们是单独的命令。

public static void uploadDirectory(FTPClient ftpClient,
String remoteDirPath, String localParentDir, String remoteParentDir)
throws IOException {

System.out.println("LISTING directory: " + localParentDir);

File localDir = new File(localParentDir);
File[] subFiles = localDir.listFiles();
if (subFiles != null && subFiles.length > 0) {
for (File item : subFiles) {
String remoteFilePath = remoteDirPath + "/" + remoteParentDir
+ "/" + item.getName();
if (remoteParentDir.equals("")) {
remoteFilePath = remoteDirPath + "/" + item.getName();
}


if (item.isFile()) {
// upload the file
String localFilePath = item.getAbsolutePath();
System.out.println("About to upload the file: " + localFilePath);
boolean uploaded = uploadSingleFile(ftpClient,
localFilePath, remoteFilePath);
if (uploaded) {
System.out.println("UPLOADED a file to: "
+ remoteFilePath);
} else {
System.out.println("COULD NOT upload the file: "
+ localFilePath);
}
} else {
// create directory on the server
boolean created = ftpClient.makeDirectory(remoteFilePath);
if (created) {
System.out.println("CREATED the directory: "
+ remoteFilePath);
} else {
System.out.println("COULD NOT create the directory: "
+ remoteFilePath);
}

// upload the sub directory
String parent = remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
parent = item.getName();
}

localParentDir = item.getAbsolutePath();
uploadDirectory(ftpClient, remoteDirPath, localParentDir,
parent);
}
}
}
}
public static boolean uploadSingleFile(FTPClient ftpClient,
String localFilePath, String remoteFilePath) throws IOException {
File localFile = new File(localFilePath);

InputStream inputStream = new FileInputStream(localFile);
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.storeFile(remoteFilePath, inputStream);
} finally {
inputStream.close();
}
}

来源:http://www.codejava.net/java-se/networking/ftp/how-to-upload-a-directory-to-a-ftp-server

关于java - 如何将目录上传到 FTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com