Java从服务器读取文件并下载到内存中
时间: 2023-04-10 18:02:34 浏览: 81
可以使用Java的IO流来读取服务器上的文件,并将其下载到内存中。以下是一个简单的示例代码:
```java
import java.io.*;
import java.net.*;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String saveDir = "/path/to/save/directory/";
try {
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// Check if the response is OK
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// Extract the file name from the content disposition header
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// Extract the file name from the URL
fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());
}
// Open input stream