java文件下载返回文件流
时间: 2024-09-23 08:07:31 浏览: 37
在Java中,当需要从服务器下载文件并将其内容作为文件流返回给客户端时,通常会通过HTTP或HTTPS协议利用`java.net.URLConnection`或第三方库如Apache HttpClient来完成。以下是一个简单的示例,展示了如何使用基础的URLConnection获取文件:
```java
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class FileDownloader {
public InputStream downloadFile(String urlString) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求属性
connection.setRequestMethod("GET");
connection.setDoOutput(true); // 如果需要保存文件,设置为true
// 获取输入流
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream; // 返回文件输入流
} else {
throw new RuntimeException("Failed to download file. Response code: " + responseCode);
}
}
public void saveToFile(InputStream inputStream, String filePath) throws IOException {
OutputStream outputStream = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
}
```
在这个例子中,`downloadFile`方法会尝试打开指定URL的连接,如果成功(HTTP状态码为200),它将返回一个`InputStream`,这个流可以被传递给`saveToFile`方法用于保存到本地文件。
阅读全文