在Android上使用Java下载文件时,您可能会遇到无法下载不寻常文件类型的问题。 这是由于默认的MimeTypeMap只支持一些通用的文件扩展名,但并不处理其他非常用扩展名。
要解决此问题,请使用MimeTypeMap与能够解析未知MimeType的第三方库一起使用。一个流行的解决方案是使用Apache Tika。
以下是代码示例:
try {
URL url = new URL("https://example.com/someuncommonfiletype.xyz");
// Instantiate Apache Tika
Tika tika = new Tika();
// Set MIME type for the file
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Content-Type", tika.detect(connection.getInputStream()));
// Download file contents
InputStream inputStream = connection.getInputStream();
File outputFile = new File("/sdcard/someuncommonfiletype.xyz");
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
} catch (Exception e) {
// handle exception
}