使用java写一个文件上传和下载不限文件
时间: 2024-02-06 13:04:30 浏览: 24
好的,下面是一个使用 Java 实现文件上传和下载的示例代码:
文件上传:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploadDemo {
public static void main(String[] args) {
String filePath = "local_file_path"; // 本地文件路径
String uploadUrl = "http://example.com/upload"; // 上传接口地址
try {
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = connection.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
int responseCode = connection.getResponseCode();
System.out.println("Server responded with " + responseCode);
fileInputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
文件下载:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloadDemo {
public static void main(String[] args) {
String fileUrl = "http://example.com/file"; // 文件下载地址
String saveDir = "local_save_directory"; // 本地保存目录
String fileName = "downloaded_file_name"; // 下载后的文件名
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(saveDir + "\\" + fileName);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("File downloaded");
inputStream.close();
outputStream.close();
} else {
System.out.println("Server responded with " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意:这只是一个简单的示例,实际应用中还需要做一些错误处理和安全性检查。