在Java中使用URL Connection类发送FTP可以通过以下步骤实现:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
URL url = new URL("ftp://ftp.example.com/file.txt");
URLConnection connection = url.openConnection();
connection.setRequestProperty("ftp.username", "username");
connection.setRequestProperty("ftp.password", "password");
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("local_file.txt"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
8. 关闭输入流和输出流:
```java
inputStream.close();
outputStream.close();
完整代码示例:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class FTPExample {
public static void main(String[] args) {
try {
URL url = new URL("ftp://ftp.example.com/file.txt");
URLConnection connection = url.openConnection();
connection.setRequestProperty("ftp.username", "username");
connection.setRequestProperty("ftp.password", "password");
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("local_file.txt"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File downloaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这种方法可以使用Java的URL Connection类来实现通过FTP发送文件。可以设置FTP用户名和密码,并将文件下载到本地。
腾讯云相关产品:腾讯云对象存储(COS)可以用于存储下载的文件。您可以参考以下链接获取更多关于腾讯云对象存储的详细信息:腾讯云对象存储(COS)产品介绍
请注意,该答案中不提及亚马逊AWS、Azure、阿里云、华为云、天翼云、GoDaddy、Namecheap、Google等流行的云计算品牌商。
领取专属 10元无门槛券
手把手带您无忧上云