一、获取到文件流并下载该文件流,当作普通文件
处理文件流并保存为文件的例子:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileStreamDownloader {
public static void downloadFileStream(String urlString, String saveFilePath) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
try {
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 创建文件输出流用于保存文件
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(saveFilePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("File downloaded successfully.");
}
} else {
throw new Exception("GET request failed with response code: " + responseCode);
}
} finally {
connection.disconnect();
}
}
public static void main(String[] args) {
try {
String urlString = "http://example.com/file/to/download";
String savePath = "local/file/path/to/save/downloaded.file";
downloadFileStream(urlString, savePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码做了以下修改:
- 方法签名和返回类型更改为处理文件下载,不再返回
JSONObject
。 - 添加了一个参数
saveFilePath
来指定保存文件的本地路径。 - 使用
FileOutputStream
代替BufferedReader
来处理输入流,这更适合处理二进制文件(如图片、文档等)。 - 读取输入流并直接写入到输出流中,直到没有更多字节可读。
- 删除了原本用于构建JSON响应的代码块,因为现在处理的是文件流而不是文本数据。
请确保替换urlString
变量的值为目标文件的URL地址,以及savePath
变量为你希望在本地保存文件的路径及文件名。
二、将获取的文件流转为 MultipartFile
要将从HTTP GET请求获得的文件流转换为MultipartFile
对象,你首先需要了解MultipartFile
通常用于处理HTTP请求中的文件上传部分,而并非直接用于处理HTTP响应中的文件流。不过,你可以创建一个自定义的类或方法来模拟MultipartFile
的行为,以便在后续操作中使用它,比如通过Spring框架的文件处理机制进行处理。
以下是一个简化的示例,展示如何将获取的输入流包装成一个模拟的MultipartFile
对象。请注意,这个例子仅作为概念上的演示,并未直接实现MultipartFile
接口的所有细节,但在很多场景下可能已经足够使用。
首先,你需要一个辅助类来模拟MultipartFile
的行为:
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import java.io.ByteArrayResource;
import java.io.IOException;
import java.io.InputStream;
public class FileStreamToMultipartFile {
/**
* 将InputStream转换为MockMultipartFile,以便模拟MultipartFile行为。
*
* @param inputStream 文件流
* @param fileName 文件名
* @return MockMultipartFile对象
* @throws IOException 如果读取输入流时发生错误
*/
public static MultipartFile convertInputStreamToMultipartFile(InputStream inputStream, String fileName) throws IOException {
byte[] byteArray = inputStream.readAllBytes();
return new MockMultipartFile(fileName, fileName, "application/octet-stream", byteArray);
}
}
然后,在你的下载方法中使用这个辅助类将文件流转换为MultipartFile
:
import org.springframework.mock.web.MockMultipartFile;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileStreamDownloader {
public static MockMultipartFile downloadAsStreamAndConvertToFile(String urlString) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
try {
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取文件流并转换为MultipartFile
try (InputStream inputStream = connection.getInputStream()) {
String[] pathParts = urlString.split("/");
String fileName = pathParts[pathParts.length - 1]; // 简单示例:从URL中提取文件名,请根据实际情况调整
return FileStreamToMultipartFile.convertInputStreamToMultipartFile(inputStream, fileName);
}
} else {
throw new Exception("GET request failed with response code: " + responseCode);
}
} finally {
connection.disconnect();
}
}
public static void main(String[] args) {
try {
String urlString = "http://example.com/file/to/download";
MockMultipartFile multipartFile = downloadAsStreamAndConvertToFile(urlString);
// 现在你可以像处理真正的MultipartFile一样处理multipartFile
System.out.println("File downloaded and converted to MultipartFile with name: " + multipartFile.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,这个方案利用了Spring框架提供的MockMultipartFile
类来模拟一个MultipartFile实例,这在单元测试或者某些特定的处理流程中非常有用。然而,如果你的应用程序不需要直接与Spring的文件上传功能集成,直接处理原始的输入流并将其保存到文件系统或其他存储服务上可能更为直接有效。
注意:
byte[] byteArray = inputStream.readAllBytes();
readAllBytes 方法可能依赖某一个jdk 版本,可以使用如下方式替代,将inputstream 转为 byte[]
将InputStream
转换为byte[]
数组的一个现代且简洁的方法是使用ByteArrayOutputStream
,结合try-with-resources语句来自动管理资源。这里是一个示例代码片段:
import java.io.*;
public class InputStreamToByteArray {
public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
return outputStream.toByteArray();
}
}
public static void main(String[] args) {
// 示例用法
try (InputStream inputStream = new FileInputStream("path/to/your/file")) {
byte[] byteArray = inputStreamToByteArray(inputStream);
// 现在 byteArray 包含了文件的全部内容
System.out.println("File converted to byte array successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这段代码首先创建了一个ByteArrayOutputStream
实例,并在一个try-with-resources块中使用它,确保即使发生异常也能正确关闭输出流。然后,它读取InputStream
的内容到缓冲区,并将缓冲区的内容写入ByteArrayOutputStream
,直到没有更多的字节可以读取(即read()
返回-1)。最后,通过调用toByteArray()
方法将输出流的内容转换为byte[]
数组。
请注意,你需要根据实际情况替换 "path/to/your/file"
为实际文件路径,并处理好可能抛出的IOException
。