【发布时间】:2017-01-22 22:46:14
【问题描述】:
我正在编写一个将文件上传到另一台设备的应用程序。我必须限制如何将文件类型共享到另一台设备。我可以检查文件扩展名,但有没有更安全的方法来检查文件是否为 apk。
【问题讨论】:
-
如果您认为我的答案涵盖了您正在寻找的内容,那么您可以将其设置为接受的答案吗?
标签: android file apk file-extension
我正在编写一个将文件上传到另一台设备的应用程序。我必须限制如何将文件类型共享到另一台设备。我可以检查文件扩展名,但有没有更安全的方法来检查文件是否为 apk。
【问题讨论】:
标签: android file apk file-extension
是的,你可以。 android apk 文件是zip archive。
因此您可以检查文件是否为 zip 文件,并确认 classes.dex 和 AndroidManifest.xml 文件存在。
【讨论】:
考虑到Passer by的思想,这里有一个检查文件是否为有效APK的方法
public static boolean isAPK(File file) {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
String dexFile = "classes.dex";
String manifestFile = "AndroidManifest.xml";
boolean hasDex = false;
boolean hasManifest = false;
try {
fis = new FileInputStream(file);
zipIs = new ZipInputStream(new BufferedInputStream(fis));
while ((zEntry = zipIs.getNextEntry()) != null) {
if (zEntry.getName().equalsIgnoreCase(dexFile)) {
hasDex = true;
} else if (zEntry.getName().equalsIgnoreCase(manifestFile)) {
hasManifest = true;
}
if (hasDex && hasManifest) {
zipIs.close();
fis.close();
return true;
}
}
zipIs.close();
fis.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return false;
}
【讨论】:
可以做这个类:
new MimeTypeMap()
根据 Android 文档应该给出正确的结果:
Two-way map that maps MIME-types to file extensions and vice versa.
【讨论】:
MimetypesFileTypeMap 在 Android SDK 中不可用。
MimeTypeMap 的答案,这是一个 android.webkit,根据文档应该可以完成这项工作
MimeTypeMap 双向映射,将 MIME 类型映射到文件扩展名,反之亦然。