io流 下载HTTP文件 上传FTP
时间: 2024-01-10 20:03:41 浏览: 30
好的,针对你的问题,我来回答一下。
首先,下载HTTP文件可以使用Java中的IO流和网络编程相关的类库来实现。具体的代码实现可以参考以下示例:
```java
import java.io.*;
import java.net.*;
public class HttpDownload {
public static void main(String[] args) throws Exception {
String fileUrl = "http://example.com/sample.pdf";
String savePath = "C:/Downloads/sample.pdf";
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
System.out.println("文件下载成功!");
}
}
```
其次,上传FTP也可以使用Java中的IO流和FTP相关的类库来实现。具体的代码实现可以参考以下示例:
```java
import java.io.*;
import org.apache.commons.net.ftp.*;
public class FtpUpload {
public static void main(String[] args) throws Exception {
String server = "ftp.example.com";
int port = 21;
String username = "ftpuser";
String password = "ftppassword";
String filePath = "C:/Uploads/sample.txt";
String remotePath = "/uploads/sample.txt";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream inputStream = new FileInputStream(new File(filePath));
boolean uploaded = ftpClient.storeFile(remotePath, inputStream);
inputStream.close();
if (uploaded) {
System.out.println("文件上传成功!");
} else {
System.out.println("文件上传失败!");
}
ftpClient.logout();
ftpClient.disconnect();
}
}
```
希望能对你有所帮助。