獲取文件格式的方法

MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)傳入的參數使用 typeFromExt 替換。android

public static void openFile( Context context, final String filePath ) {
    String ext = filePath.substring( filePath.lastIndexOf( '.' ) ).toLowerCase( Locale.US );
    try {
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String temp = ext.substring( 1 );
        String mime = mimeTypeMap.getMimeTypeFromExtension( temp );

        Intent intent = new Intent();
        intent.setAction( android.content.Intent.ACTION_VIEW );
        File file = new File( filePath );
        intent.setDataAndType( Uri.fromFile( file ), mime );
        context.startActivity( intent );
    } catch ( Exception e ) {
        e.printStackTrace();
        Toast.makeText( context, "沒法打開後綴名爲." + ext + "的文件!",
                Toast.LENGTH_LONG ).show();
    }
}
相關文章
相關標籤/搜索