java下载文件并获取文件类型
时间: 2023-08-14 16:03:47 浏览: 60
可以使用Java的URLConnection和URL来下载文件,并且可以通过文件流获取文件类型。以下是一个简单的示例代码:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void downloadFile(String fileUrl, String saveFilePath) throws Exception {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully!");
// 获取文件类型
String contentType = conn.getContentType();
System.out.println("File type: " + contentType);
}
public static void main(String[] args) {
String fileUrl = "https://example.com/sample.pdf";
String saveFilePath = "C:\\Downloads\\sample.pdf";
try {
downloadFile(fileUrl, saveFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们通过URL打开一个连接,然后获取输入流并将其写入文件输出流中,最后关闭输入输出流。在下载完成后,我们使用`conn.getContentType()`方法获取文件类型。你只需要修改`fileUrl`和`saveFilePath`参数即可下载其他文件并获取文件类型。