gpt4 book ai didi

java - 是否可以使用java从远程路径检索文件?

转载 作者:太空宇宙 更新时间:2023-11-04 12:28:49 25 4
gpt4 key购买 nike

我的任务是自动化一个流程,每天从 WinSCP 客户端提取文件。到目前为止,我已经能够自动登录并为要运行的代码设置定期计划;然而我似乎遇到了障碍。当我尝试查找要检索的文件时,没有任何反应。这是因为我希望访问的文件是通过远程目录。我几乎确信我编写的代码没有错误。我只是不确定是否指定 java 可以找到该文件的某个路径。我不知道如何告诉java代码从哪里提取这个文件。有什么想法吗?

最佳答案

您可以尝试使用以下代码:

更多详情可查看here .

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

/**
* A program demonstrates how to upload files from local computer to a remote
* FTP server using Apache Commons Net API.
* @author www.codejava.net
*/
public class FTPDownloadFileDemo {

public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";

FTPClient ftpClient = new FTPClient();
try {

ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "/test/video.mp4";
File downloadFile1 = new File("D:/Downloads/video.mp4");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();

if (success) {
System.out.println("File #1 has been downloaded successfully.");
}

// APPROACH #2: using InputStream retrieveFileStream(String)
String remoteFile2 = "/test/song.mp3";
File downloadFile2 = new File("D:/Downloads/song.mp3");
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream2.write(bytesArray, 0, bytesRead);
}

success = ftpClient.completePendingCommand();
if (success) {
System.out.println("File #2 has been downloaded successfully.");
}
outputStream2.close();
inputStream.close();

} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

关于java - 是否可以使用java从远程路径检索文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38080733/

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