【Android】oui.txt格式化的sqlite数据库文件直接导入

来源:互联网 发布:js原型链继承 编辑:程序博客网 时间:2024/06/05 00:52

oui官方地址: http://standards-oui.ieee.org/oui.txt



sqlite数据库文件:http://download.csdn.net/download/u013372185/10048809


图标资源:http://download.csdn.net/download/u013372185/10048889



帮助类(导入和查询):DeviceFactoryDBHandle

package xxx;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.SQLException;import android.database.sqlite.SQLiteDatabase;import android.os.Environment;import android.util.Log;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.concurrent.Executor;import java.util.concurrent.Executors;/** * '设备厂家'数据库操作类 * Created by Administrator on 2017/3/14 0014. */public class DeviceFactoryDBHandle {    private final int BUFFER_SIZE = 400000;    public static final String DB_NAME = "device_factory.db"; //保存的数据库文件名    public static final String PACKAGE_NAME = "com.xxx.yourpackage";    public static final String DB_PATH = "/data"            + Environment.getDataDirectory().getAbsolutePath() + "/"            + PACKAGE_NAME+"/databases/";  //在手机里存放数据库的位置(/data/data/com.xxx.yourpackage/databases/device_factory.db)    public static Object lock = new Object();    private static DeviceFactoryDBHandle instance;    private  SQLiteDatabase db;    public static DeviceFactoryDBHandle getInstance() {        if(instance == null){            instance = new DeviceFactoryDBHandle();        }        return instance;    }    public DeviceFactoryDBHandle() {        db = openDatabase(DB_PATH + DB_NAME);    }    /**     * 保存厂家MAC信息到本地数据库(一条记录间隔20ms,oui.txt有效记录22919条,7'20'')     * @param context     */    public static void saveFactoryFromFile(final Context context) {        Log.i("TAG", "saveFactoryFromFile: "+MySharedPreference.isSaveDeviceFactoryComplete());        if (!MySharedPreference.isSaveDeviceFactoryComplete()) {            Executor threadPool = Executors.newCachedThreadPool();            //先清空原先残余数据            DeviceFactoryDBHandle.deleteAll();            MySharedPreference.setReadFinishOutCount(0);            for (int i = 1; i <= 13; i++) {                final int index = i;                Thread thread =  new Thread(new Runnable() {                    @Override                    public void run() {//                        List<DeviceFactoryEntity> list = DataSupport.findAll(DeviceFactoryEntity.class);                        //再读文件,存数据库                        try {                            String fileName = String.format("oui_%d.txt", index);//                            System.out.println("filename-->"+fileName);                            InputStream ouiInputStream = context.getResources().getAssets().open(fileName);                            FileUtils.readEachLine(ouiInputStream, new FileUtils.CallBackReadLine() {                                @Override                                public void read(String eachLine) {                                    if (eachLine.contains("(base 16)")) {                                        eachLine = eachLine.replace("(base 16)", "");                                        String[] list = eachLine.split("\\t\\t");//                                    System.out.println(list[0] + "  " + list[1]);                                        //1-先保存到列表(读取完之后,再把列表数据一起存到数据库,用此模式可提高效率,如果用save一条条保存会很慢)                                        DeviceFactoryEntity entity = new DeviceFactoryEntity();                                        entity.setThreeByteMac(list[0].trim().toUpperCase());                                        entity.setFactory(list[1].trim().toLowerCase());                                        MyApplication.getInstance().getDeviceFactoryEntities().add(entity);                                    }                                }                                @Override                                public void end(long lineLength) {                                    synchronized (lock){                                    MySharedPreference.setReadFinishOutCount(MySharedPreference.getReadFinishOutCount() + 1);                                    Log.i("TAG", "end: 厂家信息一个文件加载完毕,当前数:" + MySharedPreference.getReadFinishOutCount());                                    if (MySharedPreference.getReadFinishOutCount() == 13) {//完全加载完毕 (22901个)                                        Log.i("TAG", "end: 列表总数:" + MyApplication.getInstance().getDeviceFactoryEntities().size());                                        //2-列表数据一起存到本地数据库                                        for (int j = 0; j < MyApplication.getInstance().getDeviceFactoryEntities().size(); j++) {                                            DeviceFactoryEntity entity = MyApplication.getInstance().getDeviceFactoryEntities().get(j);                                            insert(entity);                                        }                                        MySharedPreference.setSaveDeviceFactoryComplete(true);                                        Log.i("TAG", "end: 厂家mac保存完毕");                                    }                                }                                }                            });                        } catch (Exception e) {                            e.printStackTrace();                        }                    }                });                thread.start();            }        }    }    public static void saveFactoryFromNet() {        //先清空本地,再更新最新厂家mac//        DataSupport.deleteAll(DeviceFactoryEntity.class);//        HttpHelp.getInstance().requestGet("http://standards-oui.ieee.org/oui/oui.txt", new FileUtils.CallBackReadLine() {//            @Override//            public void read(String eachLine) {//                if(eachLine.contains("(base 16)")){//                    eachLine = eachLine.replace("(base 16)","");//                    String[] list = eachLine.split("\\t\\t");//                    System.out.println(list[0]+"  "+list[1]);////                    //保存到本地数据库//                    DeviceFactoryEntity entity = new DeviceFactoryEntity();//                    entity.setThreeByteMac(list[0].trim().toUpperCase());//                    entity.setFactory(list[1].trim().toLowerCase());//                    entity.save();//                }//            }////            @Override//            public void end(long lineLength) {//                DeviceFactoryEntity entity = DataSupport.find(DeviceFactoryEntity.class,1);//                System.out.println("结束--"+lineLength+"   "+entity.getThreeByteMac()+","+entity.getFactory());////            }//        });    }    public static void  insert( DeviceFactoryEntity entity){        if(entity !=null){//这里必须要加非空判断            ContentValues values = new ContentValues();            values.put("three_byte_mac",entity.getThreeByteMac());            values.put("factory",entity.getFactory());//            DBHelperForFactory.getInstance().getDb().insert("device_factory_entity",null,values);            getInstance().db.insert("device_factory_entity",null,values);        }    }    public static void deleteAll(){        try {            String sql_delete_data = "DELETE  FROM device_factory_entity";//            DBHelperForFactory.getInstance().getDb().execSQL(sql_delete_data);            getInstance().db.execSQL(sql_delete_data);        } catch (SQLException e) {            e.printStackTrace();        }    }    public static void delete(String threeByteMac){        String sql_delete_data = "DELETE  FROM device_factory_entity WHERE three_byte_mac = '"+threeByteMac+"'";//        DBHelperForFactory.getInstance().getDb().execSQL(sql_delete_data);        getInstance().db.execSQL(sql_delete_data);    }    /**     * 查询     * @param threeByteMac 查询条件:前3字节MAC     * @param isLike  是否要模糊查询     * @return  查询结果     */    public static ArrayList<DeviceFactoryEntity> query(String threeByteMac,boolean isLike){        ArrayList<DeviceFactoryEntity> list  = new ArrayList<>();//        SQLiteDatabase db = DBHelperForFactory.getInstance().getWritableDatabase();        SQLiteDatabase db = getInstance().db;        Cursor cursor;        if(isLike){//            cursor = db.rawQuery("SELECT * FROM device_factory_entity",null);            cursor = db.rawQuery("SELECT * FROM device_factory_entity WHERE three_byte_mac like ?", new String[]{"%"+threeByteMac+"%"});        }else{            cursor = db.rawQuery("SELECT * FROM device_factory_entity WHERE three_byte_mac = ? ", new String[]{""+threeByteMac});        }        if(cursor !=null){            while (cursor.moveToNext()){                String three_byte_mac  = cursor.getString(cursor.getColumnIndex("three_byte_mac"));                String factory = cursor.getString(cursor.getColumnIndex("factory"));                DeviceFactoryEntity entity = new DeviceFactoryEntity();                entity.setThreeByteMac(three_byte_mac);                entity.setFactory(factory);                list.add(entity);            }            cursor.close();//            Log.i("TAG", "查询成功--结果数:"+list.size());        }else{//            Log.i("TAG", "query--NULL: 查询失败");        }        return list;    }    /**     * 本地导入数据库文件     * @param dbfile     * @return     */    private SQLiteDatabase openDatabase(String dbfile) {        try {            if (!(new File(dbfile).exists())) {                Log.i("TAG", "openDatabase: 数据库device_factory.db不存在,开始本地导入");                //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库                InputStream is = MyApplication.getInstance().getResources().openRawResource(                        R.raw.device_factory); //欲导入的数据库                FileOutputStream fos = new FileOutputStream(dbfile);                byte[] buffer = new byte[BUFFER_SIZE];                int count = 0;                while ((count = is.read(buffer)) > 0) {                    fos.write(buffer, 0, count);                }                fos.close();                is.close();            }else{                Log.i("TAG", "openDatabase: 数据库device_factory.db已存在(无需导入)");            }            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,null);            MySharedPreference.setSaveDeviceFactoryComplete(true);            Log.i("TAG", "openDatabase:打开数据库成功-device_factory.db");            return db;        } catch (FileNotFoundException e) {            Log.e("Database", "File not found");            e.printStackTrace();        } catch (IOException e) {            Log.e("Database", "IO exception");            e.printStackTrace();        }        return null;    }}

用这个工具类直接调查询就行了,第一次调用时候会自动导入数据库:

List<DeviceFactoryEntity> findList = DeviceFactoryDBHandle.query(threeByteMac,true);

实体类:

public class DeviceFactoryEntity {    private long id;    private String threeByteMac= "";//mac前3个字节(38BC1A)    private String factory= "";//完整的厂家名称(d-link international)    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getThreeByteMac() {        return threeByteMac;    }    public void setThreeByteMac(String threeByteMac) {        this.threeByteMac = threeByteMac;    }    public String getFactory() {        return factory;    }    public void setFactory(String factory) {        this.factory = factory;    }}

常量类-DeviceConstant:

package com.xxx.constant;import java.util.HashMap;import java.util.List;import java.util.Map;/** * 设备常量(厂家名称,logo) * Created by Administrator on 2017/3/13 0013. */public class DeviceConstant {    public static Map<Integer, String> CN_ROUTER_NAME_MAP = new HashMap<>();    public static Map<Integer, String> CN_ANDROID_NAME_MAP = new HashMap<>();    public static Map<Integer, String> CN_IOS_NAME_MAP = new HashMap<>();    static {        CN_IOS_NAME_MAP.put(0, "苹果");        CN_IOS_NAME_MAP.put(59, "未知厂家");        CN_ROUTER_NAME_MAP.put(1, "阿鲁巴");        CN_ROUTER_NAME_MAP.put(2, "华硕");        CN_ROUTER_NAME_MAP.put(3, "傲天动联");        CN_ROUTER_NAME_MAP.put(4, "贝尔金");        CN_ROUTER_NAME_MAP.put(8, "思科");        CN_ROUTER_NAME_MAP.put(10, "大唐");        CN_ROUTER_NAME_MAP.put(12, "友讯");        CN_ROUTER_NAME_MAP.put(15, "迅捷");        CN_ROUTER_NAME_MAP.put(17, "烽火科技");        CN_ROUTER_NAME_MAP.put(19, "国人通信");        CN_ROUTER_NAME_MAP.put(20, "华3");        CN_ROUTER_NAME_MAP.put(36, "水星");        CN_ROUTER_NAME_MAP.put(39, "磊科");        CN_ROUTER_NAME_MAP.put(40, "网件");        CN_ROUTER_NAME_MAP.put(53, "腾达");        CN_ROUTER_NAME_MAP.put(34, "万利达");        CN_ROUTER_NAME_MAP.put(50, "星网锐捷");        CN_ROUTER_NAME_MAP.put(56, "TP-LinK");        CN_ROUTER_NAME_MAP.put(59, "未知厂家");        CN_ANDROID_NAME_MAP.put(27, "华为");        CN_ANDROID_NAME_MAP.put(63, "小米");        CN_ANDROID_NAME_MAP.put(35, "魅族");        CN_ANDROID_NAME_MAP.put(47, "三星");        CN_ANDROID_NAME_MAP.put(44, "OPPO");        CN_ANDROID_NAME_MAP.put(43, "一加");        CN_ANDROID_NAME_MAP.put(45, "飞利浦");        CN_ANDROID_NAME_MAP.put(41, "洛基亚");        CN_ANDROID_NAME_MAP.put(31, "联想");        CN_ANDROID_NAME_MAP.put(65, "中兴");        CN_ANDROID_NAME_MAP.put(66, "锤子科技");        CN_ANDROID_NAME_MAP.put(49, "索尼");        CN_ANDROID_NAME_MAP.put(32, "LG");        CN_ANDROID_NAME_MAP.put(21, "海信");        CN_ANDROID_NAME_MAP.put(26, "HTC");        CN_ANDROID_NAME_MAP.put(25, "惠普");        CN_ANDROID_NAME_MAP.put(28, "英特尔");        CN_ANDROID_NAME_MAP.put(38, "摩托罗拉");        CN_ANDROID_NAME_MAP.put(59, "未知厂家");    }    /**     * 主要厂商名称(66个)     */    public static String[] MAIN_FACTORY_NAME = new String[]{            "apple", "aruba", "asus", "autelan",            "belkin", "bhu", "buffalo",            "cctf", "cisco", "comba",            "datang", "dell", "dlink", "dowell",            "ericsson",            "fast", "feixun", "fiberhome", "fujitsu",            "grentech",            "h3c", "hisense", "hiwifi", "honghai"            , "honghao", "hp", "htc", "huawei",            "intel", "jinli", "jse",            "lenovo", "lg", "liteon",            "malata", "meizu", "mercury", "meru", "moto",            "netcore", "netgear", "nokia",            "omron", "oneplus", "oppo",            "philips",            "router_unkown",            "samsung", "shanzhai"            , "sony", "start_net", "sunyuanda",            "tcl", "tenda", "texas", "tianyu", "tp-link",            "ubq", "undefine", "unknown", "utstarcom",            "volans",            "xerox", "xiaomi",            "zdc", "zhongxing", "smartisan"};    /**     * 主要厂商灰色图片资源(66个)     */    public static int[] MAIN_FACTORY_GRAY_RESID = {            R.mipmap.logo_apple_gray,            R.mipmap.logo_aruba_gray,            R.mipmap.logo_asus_gray,            R.mipmap.logo_autelan_gray,            R.mipmap.logo_belkin_gray,            R.mipmap.logo_bhu_gray,            R.mipmap.logo_buffalo_gray,            R.mipmap.logo_cctf_gray,            R.mipmap.logo_cisco_gray,            R.mipmap.logo_comba_gray,            R.mipmap.logo_datang_gray,            R.mipmap.logo_dell_gray,            R.mipmap.logo_dlink_gray,            R.mipmap.logo_dowell_gray,            R.mipmap.logo_ericsson_gray,            R.mipmap.logo_fast_gray,            R.mipmap.logo_feixun_gray,            R.mipmap.logo_fiberhome_gray,            R.mipmap.logo_fujitsu_gray,            R.mipmap.logo_grentech_gray,            R.mipmap.logo_h3c_gray,            R.mipmap.logo_hisense_gray,            R.mipmap.logo_hiwifi_gray,            R.mipmap.logo_honghai_gray,            R.mipmap.logo_honghao_gray,            R.mipmap.logo_hp_gray,            R.mipmap.logo_htc_gray,            R.mipmap.logo_huawei_gray,            R.mipmap.logo_intel_gray,            R.mipmap.logo_jinli_gray,            R.mipmap.logo_jse_gray,            R.mipmap.logo_lenovo_gray,            R.mipmap.logo_lg_gray,            R.mipmap.logo_liteon_gray,            R.mipmap.logo_malata_gray,            R.mipmap.logo_meizu_gray,            R.mipmap.logo_mercury_gray,            R.mipmap.logo_meru_gray,            R.mipmap.logo_moto_gray,            R.mipmap.logo_netcore_gray,            R.mipmap.logo_netgear_gray,            R.mipmap.logo_nokia_gray,            R.mipmap.logo_omron_gray,            R.mipmap.logo_oneplus_gray,            R.mipmap.logo_oppo_gray,            R.mipmap.logo_philips_gray,            R.mipmap.logo_router_unkown,            R.mipmap.logo_samsung_gray,            R.mipmap.logo_shanzhai_gray,            R.mipmap.logo_sony_gray,            R.mipmap.logo_start_net_gray,            R.mipmap.logo_sunyuanda_gray,            R.mipmap.logo_tcl_gray,            R.mipmap.logo_tenda_gray,            R.mipmap.logo_texas_gray,            R.mipmap.logo_tianyu_gray,            R.mipmap.logo_tplink_gray,            R.mipmap.logo_ubq_gray,            R.mipmap.logo_undefine_gray,            R.mipmap.logo_unknown_gray,            R.mipmap.logo_utstarcom_gray,            R.mipmap.logo_volans_gray,            R.mipmap.logo_xerox_gray,            R.mipmap.logo_xiaomi_gray,            R.mipmap.logo_zdc_gray,            R.mipmap.logo_zhongxing_gray,            R.mipmap.logo_smartisan,    };    /**     * 主要厂商正常色图片资源(66个)     */    public static int[] MAIN_FACTORY_RESID = {            R.mipmap.logo_apple,            R.mipmap.logo_aruba,            R.mipmap.logo_asus,            R.mipmap.logo_autelan,            R.mipmap.logo_belkin,            R.mipmap.logo_bhu,            R.mipmap.logo_buffalo,            R.mipmap.logo_cctf,            R.mipmap.logo_cisco,            R.mipmap.logo_comba,            R.mipmap.logo_datang,            R.mipmap.logo_dell,            R.mipmap.logo_dlink,            R.mipmap.logo_dowell,            R.mipmap.logo_ericsson,            R.mipmap.logo_fast,            R.mipmap.logo_feixun,            R.mipmap.logo_fiberhome,            R.mipmap.logo_fujitsu,            R.mipmap.logo_grentech,            R.mipmap.logo_h3c,            R.mipmap.logo_hisense,            R.mipmap.logo_hiwifi,            R.mipmap.logo_honghai,            R.mipmap.logo_honghao,            R.mipmap.logo_hp,            R.mipmap.logo_htc,            R.mipmap.logo_huawei,            R.mipmap.logo_intel,            R.mipmap.logo_jinli,            R.mipmap.logo_jse,            R.mipmap.logo_lenovo,            R.mipmap.logo_lg,            R.mipmap.logo_liteon,            R.mipmap.logo_malata,            R.mipmap.logo_meizu,            R.mipmap.logo_mercury,            R.mipmap.logo_meru,            R.mipmap.logo_moto,            R.mipmap.logo_netcore,            R.mipmap.logo_netgear,            R.mipmap.logo_nokia,            R.mipmap.logo_omron,            R.mipmap.logo_oneplus,            R.mipmap.logo_oppo,            R.mipmap.logo_philips,            R.mipmap.logo_router_unkown,            R.mipmap.logo_samsung,            R.mipmap.logo_shanzhai,            R.mipmap.logo_sony,            R.mipmap.logo_start_net,            R.mipmap.logo_sunyuanda,            R.mipmap.logo_tcl,            R.mipmap.logo_tenda,            R.mipmap.logo_texas,            R.mipmap.logo_tianyu,            R.mipmap.logo_tplink,            R.mipmap.logo_ubq,            R.mipmap.logo_undefine,            R.mipmap.logo_unknown,            R.mipmap.logo_utstarcom,            R.mipmap.logo_volans,            R.mipmap.logo_xerox,            R.mipmap.logo_xiaomi,            R.mipmap.logo_zdc,            R.mipmap.logo_zhongxing,            R.mipmap.logo_smartisan    };    /**     * 用mac匹配,找到对应厂家,然后返回厂家列表下标     *     * @param threeByteMac     * @return     */    public static int findIndexByMac(String threeByteMac) {        int index = 59;//默认未知//        Log.i("TAG", "测试7.0: "+ DeviceConstant.MAIN_FACTORY_NAME.length);//        List<DeviceFactoryEntity> findList = DataSupport.where(" ThreeByteMac like ? ", "" + threeByteMac + "%25").//                find(DeviceFactoryEntity.class);//原查询,7.0设备有异常,不用        List<DeviceFactoryEntity> findList = DeviceFactoryDBHandle.query(threeByteMac,true);        if (findList.size() != 0) {            for (int i = 0; i < DeviceConstant.MAIN_FACTORY_NAME.length; i++) {                if (findList.get(0).getFactory().toLowerCase().contains(DeviceConstant.MAIN_FACTORY_NAME[i])) {                    index = i;//                    System.out.println("厂家  " + DeviceConstant.MAIN_FACTORY_NAME[i]);                }            }        }        return index;    }    public enum Type {UNKNOW, ANDROID, IOS, ROUTER}    /**     * 获取工厂中文名称     *     * @param index 下标     * @return     */    public static Object[] getFactoryChineseName(int index) {        System.out.println("CN_ANDROID_NAME_MAP---"+CN_ANDROID_NAME_MAP.size());        Object[] res = new Object[2];        Type type = Type.UNKNOW;        String ChineseName = "未知厂家";        res[0] = type;        res[1] = ChineseName;        System.out.println("index---"+index);        ChineseName = CN_ANDROID_NAME_MAP.get(index);        if (ChineseName != null) {            type = Type.ANDROID;            res[0] = type;            res[1] = ChineseName;            return res;        }        ChineseName = CN_IOS_NAME_MAP.get(index);        if (ChineseName != null) {            type = Type.IOS;            res[0] = type;            res[1] = ChineseName;            return res;        }        ChineseName = CN_ROUTER_NAME_MAP.get(index);        if (ChineseName != null) {            type = Type.ROUTER;            res[0] = type;            res[1] = ChineseName;            return res;        }        return res;    }}



----------------------------------------

旧方式(非导入):直接生成数据库,需要调用上面DeviceFactoryDBHandle的插入数据方法

 protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mContext = this;                //载入厂家信息(暂不用,改为直接导入数据库文件)//        try {//            DeviceFactoryDBHandle.saveFactoryFromFile(this);//        } catch (Exception e) {//            e.printStackTrace();//        }}










原创粉丝点击