温馨提示×

Java怎么实现文件上传和下载功能

小亿
101
2023-08-01 10:24:07
栏目: 编程语言

在Java中实现文件上传和下载功能可以使用Java的文件操作类和网络编程类来实现。下面是一个简单的示例代码:

文件上传功能:

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileUploader {
public static void main(String[] args) {
String fileToUpload = "path/to/file.txt";
String uploadUrl = "http://example.com/upload";
try {
// 创建URL对象
URL url = new URL(uploadUrl);
// 创建连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 允许输入输出流
connection.setDoInput(true);
connection.setDoOutput(true);
// 创建数据输出流
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// 读取文件内容并写入输出流
Path path = Paths.get(fileToUpload);
byte[] fileContent = Files.readAllBytes(path);
outputStream.write(fileContent);
// 关闭输出流
outputStream.flush();
outputStream.close();
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

文件下载功能:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDownloader {
public static void main(String[] args) {
String downloadUrl = "http://example.com/file.txt";
String savePath = "path/to/save/file.txt";
try {
// 创建URL对象
URL url = new URL(downloadUrl);
// 创建连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 获取输入流
InputStream inputStream = connection.getInputStream();
// 创建文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
// 读取输入流内容并写入文件输出流
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 关闭流
inputStream.close();
fileOutputStream.close();
connection.disconnect();
System.out.println("File downloaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

以上代码中的fileToUploaddownloadUrl分别是要上传和下载的文件的路径或URL。在实际使用时,需要将它们替换为实际的文件路径或URL。同时,还需要注意文件路径的正确性和访问权限。

0