java - 用Java将字节数组上传到FTP
问题描述
我的目标是能够将文件上传到 FTP 服务器,我进行了一些研究,并看到了如果文件已经存储在本地,如何上传文件的方法,我有一个返回的函数,byte[]
所以我想知道如何发送该文件如果文件存在于内存中,则发送到 FTP 服务器。
private void connect() throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftpClient.connect(ftp.getServer(), ftp.getPort());
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new RuntimeException("Could not connect to FTP Server");
} else {
ftpClient.login(ftp.getUser(), ftp.getPassword());
}
}
解决方案
您似乎正在使用 Apache Commons Net FTPClient
。
它实际上甚至没有直接上传物理文件的方法。它的FTPClient.storeFile
方法只接受InputStream
接口。
通常您会使用FileInputStream
来指代物理文件:
如何将文件上传到 FTP 服务器?
当您想使用时ByteArrayInputStream
:
我们可以将字节数组转换为 Java 中的 InputStream 吗?
InputStream inputStream = new ByteArrayInputStream(bytes);
ftpClient.storeFile(remotePath, inputStream);
推荐阅读
- java - 外部进程能否强制 JVM 抛出“java.lang.OutOfMemoryError:GC 开销限制超出”
- continuous-integration - 本地地形开发:计划但不适用?
- javascript - 如何使用 React 获取局域网中的计算机名称和本地 IP 地址
- python - 在 Twitter 情感分析上用 Python 中的 LIME 文本解释器解释我的深度学习模型
- react-native - ReactNative 抽屉导航自定义页脚
- r - 按人计算的小时数
- python - 使用没有 Databricks 的 scala 将 spark 3.0 sql 数据帧写入 CSV 文件时出错
- python - 将 DataFrame 连接到多索引 df 保持原始多索引
- sql - Oracle数据库多表删除问题
- delphi - Fastreport VCL 6.8交叉表值字段中的文本给出错误