用java设计一个文件上传下载的工具类
时间: 2024-06-09 21:05:20 浏览: 8
好的,以下是一个基于Java的文件上传下载工具类的示例代码:
```
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class FileUploaderDownloader {
/**
* 上传文件到指定URL
* @param file 要上传的文件
* @param uploadUrl 上传文件的URL
* @throws IOException
*/
public static void uploadFile(File file, String uploadUrl) throws IOException {
URL url = new URL(uploadUrl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0");
OutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "--" + "*****" + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
out.write(content.getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes());
in.close();
out.write(("--" + "*****" + "--" + "\r\n").getBytes());
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
/**
* 下载文件到本地
* @param downloadUrl 下载文件的URL
* @param savePath 文件保存路径,包括文件名
* @throws IOException
*/
public static void downloadFile(String downloadUrl, String savePath) throws IOException {
URL url = new URL(downloadUrl);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
out.close();
in.close();
}
}
```
使用示例:
上传文件:
```
File file = new File("path/to/file");
String uploadUrl = "http://example.com/upload";
FileUploaderDownloader.uploadFile(file, uploadUrl);
```
下载文件:
```
String downloadUrl = "http://example.com/download/file";
String savePath = "path/to/save/file";
FileUploaderDownloader.downloadFile(downloadUrl, savePath);
```