java服务器下载文件
时间: 2023-09-25 08:06:51 浏览: 49
要在Java服务器中下载文件,可以使用Java的URL和URLConnection类。以下是一个简单的示例代码:
```java
import java.io.*;
import java.net.*;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.zip";
String saveDir = "/path/to/save/dir/";
try {
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// 检查是否成功连接
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
// 如果Content-Disposition头部存在,则使用它作为文件名
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// 否则从URL中获取文件名
fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());
}
// 在控制台上输出文件信息
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// 打开输入流和输出流
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
// 从输入流中读取数据并写入输出流中
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭输入流和输出流
outputStream.close();
inputStream.close();
System.out.println("文件下载完成");
} else {
System.out.println("文件下载失败,响应码为 " + responseCode);
}
httpConn.disconnect();
} catch (IOException e) {
System.out.println("文件下载失败:" + e.getMessage());
e.printStackTrace();
}
}
}
```
在上面的代码中,`fileUrl`变量包含要下载的文件的URL,`saveDir`变量包含要保存文件的目录。程序首先使用`URL`类创建一个对文件URL的连接,然后使用`HttpURLConnection`类打开连接并获取响应代码。如果响应代码为`HTTP_OK`,则程序从响应头中获取文件名和类型,并打开输入流和输出流。最后,程序从输入流中读取数据并写入输出流中,然后关闭输入流和输出流。