用Java写一个简单的文件上传下载代码
时间: 2024-05-17 11:18:26 浏览: 12
好的,以下是一个简单的Java文件上传和下载的示例代码,供您参考:
文件上传:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) throws IOException {
String uploadUrl = "http://localhost:8080/upload"; // 上传地址
String filePath = "path/to/file"; // 本地文件路径
File file = new File(filePath);
if (!file.exists()) {
System.out.println("File not found!");
return;
}
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Content-Disposition", "attachment;filename=" + file.getName());
OutputStream out = connection.getOutputStream();
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("File uploaded successfully!");
} else {
System.out.println("File upload failed. Response code: " + responseCode);
}
}
}
```
文件下载:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://localhost:8080/files/file.txt"; // 文件下载地址
String savePath = "path/to/save/file.txt"; // 本地保存路径
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
System.out.println("File downloaded successfully!");
} else {
System.out.println("File download failed. Response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
需要注意的是,文件上传和下载的具体实现方式,可能会因为上传/下载的服务器和协议等原因而略有不同。上述代码仅供参考。