GVKun编程网logo

RedisSingleUtils 工具类(redisutils工具类方法)

5

本文将介绍RedisSingleUtils工具类的详细情况,特别是关于redisutils工具类方法的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于

本文将介绍RedisSingleUtils 工具类的详细情况,特别是关于redisutils工具类方法的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)、Android-FileUtils-工具类、cocos2d::CCFileUtils::sharedFileUtils()->getFileData(szFile, "r", &bufferSize) 不同平台返回值不一样、cocos2dx CCFileUtils::sharedFileUtils() 静态调用的知识。

本文目录一览:

RedisSingleUtils 工具类(redisutils工具类方法)

RedisSingleUtils 工具类(redisutils工具类方法)

RedisSingleUtils.java 

package com.common.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ch.fm.system.dictionary.entity.DictionaryDetailEntity;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * <p>
 *  redis工具类
 * </p>
 * @author why
 * @date 2016-7-20上午11:12:28
 */
public class RedisSingleUtils {
    public static Logger  logger = LoggerFactory.getLogger(RedisSingleUtils.class);
    private static JedisPool jedisPool = null;

    static {
        //从属性文件读取配置
        ResourceBundle bundle = ResourceBundle.getBundle("conf.system.system",Locale.CHINESE);
        String host = bundle.getString("redis.host");
        String port = bundle.getString("redis.port");
        int index = StrUtil.isNullOrBlank(bundle.getString("redis.index"))?Integer.valueOf(bundle.getString("redis.index")):0;
        String auth = null; //bundle.getString("redis.auth");

        try {
            JedisPoolConfig config = new JedisPoolConfig();
            //config.setMaxTotal(500);
            config.setMaxIdle(50);
            //config.setMaxWaitMillis(1000);
            config.setMaxWait(1000);
            config.setTestOnBorrow(true);
            // 在还回给pool时,是否提前进行validate操作
            config.setTestOnReturn(true);
            //连接池设置
            jedisPool = new JedisPool(config, host, Integer.parseInt(port), 1800000, auth, index);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    
    /**
     * <p>
     *  获得REDIS客户端
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:40:08
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public static void closeJedis(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
            //jedis.close();
        }
    }
    
    /**
     * <p>
     *  获得KEY所指定的对象。
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午4:21:14
     * @param key
     */
    public static Object getObjectByKey(String key){
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            String type = jedis.type(key);
            if("string".equalsIgnoreCase(type)){
                return jedis.get(key);
            }else if("hash".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
                //map对应的类型 相当于 redis中的hash
                return jedis.hgetAll(key);
            }else if("list".equalsIgnoreCase(type)){
                Long size = jedis.llen(key);
                return jedis.lrange(key, 0, size);
            }else if("set".equalsIgnoreCase(type)){
                return jedis.smembers(key);
            }else if("zset".equalsIgnoreCase(type)){
                //有序结果集和无序结果集是一样的,都是SET
                //Long size = jedis.zrank(key, member)(key);
                 return jedis.zrange(key, 0, 10);
            }else{
                return null;
            }
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return null;
    }
    
    /**
     * <p>
     *  获得KEY所指定的对象。
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午3:09:13
     * @param key 键
     * @param value 值
     * @param isCover 如果已经存在KEY:是否覆盖
     * @return
     */
    public static  Object setObjectByKey(String key,Object value,boolean isCover){
        if(null == key || "".equals(key) || key.isEmpty()){
            logger.info("key不能空!");
            return false;
        }
        if(null == value || "".equals(value)){
            logger.info("value不能空!");
            return false;
        }
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            boolean isExists = jedis.exists(key);
            if(isExists && isCover){
                jedis.del(key);
            }
            String type = jedis.type(key);
            
            if(value instanceof String){//字符串处理
                if(isExists && !isCover && !"string".equals(type)){
                    throw new RuntimeException("类型不匹配!不能添加");
                }else{
                    jedis.set(key, value.toString());
                    return true;
                }
            }else if(value instanceof List){//LIST处理
                if(isExists && !isCover && !"list".equals(type)){
                    throw new RuntimeException("类型不匹配!不能添加");
                }else{
                    List<Object> list = (List)value;
                    if(null == list || list.size()==0){
                        throw new RuntimeException("对象集合为空!");
                    }
                    for(Object obj:list){
                        String temp = JsonUtil.getJSONString(obj);
                        jedis.lpush(key,temp);
                    }
                    return true;
                }
            }else if(value instanceof Map){//MAP处理
                if(isExists && !isCover && !"hash".equals(type)){
                    throw new RuntimeException("类型不匹配!不能添加");
                }
                Map map = (Map)value;
                if(null == map || map.size()==0){
                    throw new RuntimeException("对象集合为空!");
                }
                jedis.hmset(key, map);
                return true;
            }else if(value instanceof Set){//set处理
                if(isExists && !isCover && !"set".equals(type)){
                    throw new RuntimeException("类型不匹配!不能添加");
                }
                Set set = (Set)value;
                if(null == set || set.size()==0){
                    throw new RuntimeException("对象集合为空!");
                }
                Iterator iterator = set.iterator();
                if(iterator.hasNext()){
                    Object obj = iterator.next();
                    jedis.sadd(key, JsonUtil.getJSONString(obj));
                }
                return true;
            }else{
                jedis.set(key, JsonUtil.getJSONString(value));
                return true;
            }
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return null;
    }
    
    /**
     * <p>
     *  获得KEY所指定的对象。
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午3:09:13
     * @param key 键
     * @param value 值
     * @param isCover 如果已经存在KEY:是否覆盖
     * @return
     */
    public static  Object setObjectToStrByKey(String key,Object value,boolean isCover){
        if(null == key || "".equals(key) || key.isEmpty()){
            logger.info("key不能空!");
            return false;
        }
        if(null == value || "".equals(value)){
            logger.info("value不能空!");
            return false;
        }
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            boolean isExists = jedis.exists(key);
            if(isExists && isCover){
                jedis.del(key);
            }
            jedis.set(key, JsonUtil.getJSONString(value));
            return true;
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return null;
    }
    
    /**
     * <p>
     *  str put
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午2:43:58
     * @param key
     * @param value
     */
    public static void strPut(String key, String value) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.set(key, value);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    
    /**
     * <p>
     *  获得KEY对应的字符串
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:40:50
     * @param key
     * @return
     */
    public static String strGet(String key) {
        String value = "";
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            value = jedis.get(key);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return value;
    }
    
    /**
     * <p>
     *  删除KEY对应的字符串
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:40:50
     * @param key
     * @return
     */
    public static Long strDel(String... key) {
        Long value = 0L;
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            value = jedis.del(key);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return value;
    }
    
    /**
     * <p>
     *  发布订阅
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:41:38
     * @param theme
     * @param message
     */
    public static void publish(String theme, String message) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.publish(theme, message);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    
    /**
     * <p>
     *  设置过期时间
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:41:54
     * @param key
     * @param seconds
     */
    public static void keyExpire(String key, int seconds) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.expire(key, seconds);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    
    /**
     * <p>
     *  判断是否存在
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:42:10
     * @param key
     * @return
     */
    public static boolean keyExists(String key) {
        boolean bool = false;
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            bool = jedis.exists(key);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return bool;
    }
    
    /**
     * <p>
     *  key对应的VALUE增加 integer.
     * </p>
     * @author wanghuihui
     * @date 2017-7-20下午1:42:26
     * @param key
     * @param integer
     */
    public static void valueIncr(String key,long integer) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.incrBy(key,integer);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }

    /**
     * <p>
     * set集合增加。
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午2:13:39
     * @param key
     * @param members
     */
    public static void setAdd(String key, String... members) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.sadd(key, members);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            //jedisPool.destroy();
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    
    /**
     * <p>
     * 如果成员是存储在键中的集合的成员,则返回1,否则返回0。
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午2:04:54
     * @param key
     * @param members
     * @return
     */
    public static boolean setExists(String key, String members) {
        Jedis jedis = null;
        boolean bool = false;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            bool = jedis.sismember(key, members);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
        return bool;
    }
    /**
     * <p>
     *  有序集合
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午3:05:13
     * @param key:键
     * @param score:排序依据,SCORE越小越前。
     * @param members :成员
     */
    public static void zSetAdd(String key, double  score , String member) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.zadd(key, score,member);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    /**
     * <p>
     * 有序集合查询:相当于排序分页查询。
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午3:24:58
     * @param key:
     * @param start 开始
     * @param limit 结束
     */
    public static void zSetQuery(String key, int  start , int limit) {
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.zrange(key, start,limit);
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    /**
     * <p>
     *  清空当前数据库
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午4:04:08
     */
    public static  void flushDBAll(){
        Jedis jedis = null;
        // 从池中获取一个jedis实例
        try {
            jedis = getJedis();
            jedis.flushDB();
        } catch (Exception e) {
            // 销毁对象
            jedisPool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 还回到连接池
            closeJedis(jedis);
        }
    }
    
    public static void main(String[] args) {
        RedisSingleUtils jedisUtil = new RedisSingleUtils();
        //jedisUtil.testAll();
        //jedisUtil.testSet();
        List<DictionaryDetailEntity> list = (List<DictionaryDetailEntity>) RedisSingleUtils.getObjectByKey("list_dic_detail");
        System.out.println(11);
        JsonUtil.getObjectArrayFromJson(list.toString());
        System.out.println(list.size());
        for(DictionaryDetailEntity dic : list){
            System.out.println(dic.getLabel());
        }
    }
    /**
     * <p>
     *  測試
     * </p>
     * @author wanghuihui
     * @date 2017-7-14下午2:33:49
     */
    private void testAll(){
        Jedis jedis = RedisSingleUtils.getJedis();
        // 设置字符串数据
        jedis.set("runoobkey", "Redis");
        jedis.set("str_01", "10");
        this.valueIncr("str_01",1);
        System.out.println(this.strGet("str_01"));
        // 获取存储的数据并输出
        System.out.println("Stored string in redis: " + jedis.get("runoobkey"));
        

        /**
         * Redis Java Hash(哈希)实例
         */
        // 设置哈希数据
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "name1");
        map.put("2", "name2");
        map.put("3", "name3");
        jedis.hmset("redisHash", map);
        // 获取存储的数据并输出
        System.out.println("Stored Hash in redis: " + jedis.hgetAll("redisHash"));

        /**
         * Redis Java List(列表)实例
         */
        // 存储数据到列表中
        jedis.lpush("redisList", "1");
        jedis.lpush("redisList", "2");
        jedis.lpush("redisList", "3");
        // 获取存储数据并输出
        List<String> redisList = jedis.lrange("redisList", 0, 10);
        for (String redis : redisList) {
            System.out.println("Stored List in redis: " + redis);
        }

        /**
         * Redis Java Set(集合)实例
         */
        // 存储数据到集合中
        jedis.sadd("redisSet", "1", "2", "3", "3");
        jedis.sadd("redisSet", "22", "43");
        //测试程序会覆盖原来的SET。
        jedis.set("redisSet", "1");
        // 获取存储数据并输出
        System.out.println("Stored Set in redis: " + jedis.smembers("redisSet"));
        
        /**
         * Redis Java ZSet(有序集合)实例
         */
        // 存储数据到有序集合中
        jedis.zadd("redisZSet", 10, "3");
        jedis.zadd("redisZSet", 20, "4");
        jedis.zadd("redisZSet", 5, "2");
        jedis.zadd("redisZSet", 3, "1");
        String ty = jedis.type("redisZSet");
        // 获取存储数据并输出
        System.out.println("Stored ZSet in redis: " + jedis.zrange("redisZSet", 0, 10));

        /**
         * 获取Reids所有的KEY
         */
        // 获取数据并输出
        Set<String> keys = jedis.keys("*");
        Set<String> keys2 = jedis.keys("*nach*");
        for (String key : keys) {
            System.out.println("Set of stored key: " + key);
            String type = jedis.type(key);
            Object value = this.getObjectByKey(key);
            if(null == value){
                System.out.println("类型为空!请检查~");
            }else if(value instanceof String){
                System.out.println("value="+value);
            }else if(value instanceof List){
                List list = (List) value;
                System.out.println(list.size());
            }else if(value instanceof Map){
                Map map2 = (Map)value;
                System.out.println(11);
            }else if(value instanceof Set){
                Set set = (Set)value;
                System.out.println(11);
            }else {
                System.out.println(value.getClass());
            }
        }
        this.flushDBAll();  //清空当前数据库
    }
    private void testSet() {
        Jedis jedis = RedisSingleUtils.getJedis();
        /**
         * SET 集合
         */
        setAdd("spinach", "mem1", "mem2", "mem3", "mem4");
        Boolean isExist = setExists("spinach","mem2");
        zSetAdd("spinachZet", 20, "mem20");
        zSetAdd("spinachZet", 2, "mem2");
        zSetAdd("spinachZet", 01, "mem01");
        zSetAdd("spinachZet", 5, "mem5");
        zSetAdd("spinachZet", 2, "mem02");
        zSetAdd("spinachZet", 6, "mem6");
        zSetAdd("spinachZet", 3, "mem3");
        zSetAdd("spinachZet", 14, "mem14");
        zSetAdd("spinachZet", 10, "mem10");
        Set<String> result = jedis.zrange("spinachZet", 0, 5);
        System.out.println(result);
        Boolean isExist2 = jedis.sismember("spinachZet","mem14");
        System.out.println(jedis.exists("spinachZet"));
        /*
        Long start = System.currentTimeMillis();
        for(int i=0;i<100000;i++){
            jedis.set("key"+i,"value # Warning: since Redis is pretty fast an outside user can try up to aaaaaaaa"+i);
        }
        Long end = System.currentTimeMillis();
        for(int i=0;i<100000;i++){
            put("key"+i,"value # Warning: since Redis is pretty fast an outside user can try up to aaaaaaaa"+i);
        }
        Long end2 =System.currentTimeMillis();
        Long t1 = end - start;
        Long t2 = end2 -end; 
        System.out.println("t1="+t1+"   t2="+t2); //t1=5942   t2=17037
        */
        
    }
    
}

 

15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)

15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)

资源文件工具类把sql脚本转换为String字符串--->交给sql工具类ExecSQLUtil执行sql

1.资源文件工具类(ResourceUtil)

  把sql脚本转换为String字符串

/**
 * 资源文件工具类
 */
public class ResourceUtil {
    /**
     * 以String方式读取整个资源串
     */
    public static String readResourceAsString(String resource ,String charset) throws Exception {
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource) ;
        ByteArrayOutputStream baos = new ByteArrayOutputStream() ;

        byte[] buf = new byte[1024] ;
        int len = -1 ;
        while((len = input.read(buf)) != -1){
            baos.write(buf , 0 , len);
        }
        return new String(baos.toByteArray() , charset) ;
    }
    /**
     * 以String方式读取整个资源串
     */
    public static String readResourceAsString(String resource) throws Exception {
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource) ;
        ByteArrayOutputStream baos = new ByteArrayOutputStream() ;

        byte[] buf = new byte[1024] ;
        int len = -1 ;
        while((len = input.read(buf)) != -1){
            baos.write(buf , 0 , len);
        }
        String sql = new String(baos.toByteArray(), Charset.defaultCharset()) ;
        //替换掉注释
        sql = sql.replaceAll("--.*\r\n", "") ;
        return sql ;
    }

    /**
     * 将资源文件读取出来,形成list
     */
    public static List<String> readResourceAsList(String resource) throws Exception {
        List<String> list = new ArrayList<String>()  ;
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
        BufferedReader br = new BufferedReader(new InputStreamReader(input)) ;
        String line = null ;
        while((line = br.readLine()) != null){
            if(!line.trim().equals("")){
                list.add(line) ;
            }
        }
        return list ;
    }
}
ResourceUtil -资源文件工具类

 

2.sql执行工具类(ExecSQLUtil)

  执行sql

package com.oldboy.umeng.spark.stat;

import com.oldboy.umeng.common.util.ResourceUtil;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

/**
 * 执行脚本工具类
 */
public class ExecSQLUtil {
    /**
     * 执行sql脚本
     */
    public static void execSQLScript(SparkSession sess, String sqlScript) throws Exception {
        //资源工具类   把sql脚本转化为String
        String sqls = ResourceUtil.readResourceAsString(sqlScript);
        String arr[] = sqls.split(";");
        for (String sql : arr) {
            if (!sql.trim().equals("")) {
                sess.sql(sql).show(1000, false);
            }
        }
    }

    /**
     * 执行sqlsStr
     */
    public static void execSQLString(SparkSession sess, String sqlString) throws Exception {
        String arr[] = sqlString.split(";");
        for (String sql : arr) {
            if (!sql.trim().equals("")) {
                sess.sql(sql).show(1000, false);
            }
        }
    }
    /**
     * 执行sqlsStr
     */
    public static Dataset<Row> execSQLString2(SparkSession sess, String sqlString) throws Exception {
        String arr[] = sqlString.split(";");
        for (int i = 0 ; i< arr.length ; i ++) {
            if (!arr[i].trim().equals("")) {
                if(i != arr.length - 1){
                    sess.sql(arr[i]).show(); ;
                }
                else{
                    return sess.sql(arr[i]) ;
                }
            }
        }
        return null ;
    }

    /**
     * 注册函数
     */
    public static void execRegisterFuncs(SparkSession sess) throws Exception {
        execSQLScript(sess, "funcs.sql");
    }




}
ExecSQLUtil 执行sql工具类

 

3.例如  清洗转储数据

/**
 * 清洗数据
 */
public class DataCleanJava {
    public static void main(String[] args) throws Exception {
        String log_sql_script_name = "data_clean_startup.sql" ;
        if(args != null && args.length > 0){
            log_sql_script_name = args[0] ;
        }
        SparkConf conf = new SparkConf();
        conf.setAppName("dataClean") ;
        conf.setMaster("local[4]") ;

        SparkSession sess = SparkSession.builder().config(conf).enableHiveSupport( ).getOrCreate();
        //先注册函数
        ExecSQLUtil.execRegisterFuncs(sess);
        //执行sql
        ExecSQLUtil.execSQLScript(sess , "data_clean_error.sql");

    }

}

 

 

 

SQL脚本

funcs.sql注册函数脚本

use big12_umeng ;
drop function if exists forkstartuplogs ;
drop function if exists forkeventlogs ;
drop function if exists forkerrorlogs ;
drop function if exists forkpagelogs ;
drop function if exists forkusagelogs ;
drop function if exists formatbyday ;
drop function if exists formatbyweek ;
drop function if exists formatbymonth ;
create TEMPORARY function forkstartuplogs as ''com.oldboy.umeng.hive.udtf.ForkStartuplogsUDTF'' ;
create TEMPORARY function forkeventlogs as ''com.oldboy.umeng.hive.udtf.ForkEventlogsUDTF'' ;
create TEMPORARY function forkerrorlogs as ''com.oldboy.umeng.hive.udtf.ForkErrorlogsUDTF'' ;
create TEMPORARY function forkpagelogs as ''com.oldboy.umeng.hive.udtf.ForkPagelogsUDTF'' ;
create TEMPORARY function forkusagelogs as ''com.oldboy.umeng.hive.udtf.ForkUsagelogsUDTF'' ;
create TEMPORARY function formatbyday as ''com.oldboy.umeng.hive.udf.FormatByDayUDF'' ;
create TEMPORARY function formatbyweek as ''com.oldboy.umeng.hive.udf.FormatByWeekUDF'' ;
create TEMPORARY function formatbymonth as ''com.oldboy.umeng.hive.udf.FormatByMonthUDF'' ;

 

Android-FileUtils-工具类

Android-FileUtils-工具类

FileUtils-工具类 是对文件操作处理的方法进行了封装,提供了公共的方法;

 

package common.library.utils;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Author Liudeli
 * @Describe:文件相关工具类
 */
public final class FileUtils {

    private FileUtils() {
        throw new UnsupportedOperationException("u can''t instantiate me...");
    }

    private static final String LINE_SEP = System.getProperty("line.separator");

    /**
     * 根据文件路径获取文件
     *
     * @param filePath 文件路径
     * @return 文件
     */
    public static File getFileByPath(final String filePath) {
        return isSpace(filePath) ? null : new File(filePath);
    }

    /**
     *  根据文件目录路径获取子目录名称(不获取二级子目录)
     * @param dirPath 文件路径
     * @return 文件目录名称
     */
    public static List<String> getFiledirList(String dirPath){
        if (dirPath == null || !isDir(dirPath)) return null;
        List<String> stringList = new ArrayList<>();
        File f = new File(dirPath);
        File[] files = f.listFiles();
        if(files != null&& files.length != 0){
            for (File file : files) {
                if (file.isDirectory()) {
                    stringList.add(file.getName());
                }
            }
        }
        return stringList;
    }
    /**
     * 判断文件是否存在
     *
     * @param filePath 文件路径
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(final String filePath) {
        return isFileExists(getFileByPath(filePath));
    }

    /**
     * 判断文件是否存在
     *
     * @param file 文件
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(final File file) {
        return file != null && file.exists();
    }

    /**
     * 重命名文件
     *
     * @param filePath 文件路径
     * @param newName  新名称
     * @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
     */
    public static boolean rename(final String filePath, final String newName) {
        return rename(getFileByPath(filePath), newName);
    }

    /**
     * 重命名文件
     *
     * @param file    文件
     * @param newName 新名称
     * @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
     */
    public static boolean rename(final File file, final String newName) {
        // 文件为空返回false
        if (file == null) return false;
        // 文件不存在返回false
        if (!file.exists()) return false;
        // 新的文件名为空返回false
        if (isSpace(newName)) return false;
        // 如果文件名没有改变返回true
        if (newName.equals(file.getName())) return true;
        File newFile = new File(file.getParent() + File.separator + newName);
        // 如果重命名的文件已存在返回false
        return !newFile.exists()
                && file.renameTo(newFile);
    }

    /**
     * 判断是否是目录
     *
     * @param dirPath 目录路径
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isDir(final String dirPath) {
        return isDir(getFileByPath(dirPath));
    }

    /**
     * 判断是否是目录
     *
     * @param file 文件
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isDir(final File file) {
        return isFileExists(file) && file.isDirectory();
    }

    /**
     * 判断是否是文件
     *
     * @param filePath 文件路径
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isFile(final String filePath) {
        return isFile(getFileByPath(filePath));
    }

    /**
     * 判断是否是文件
     *
     * @param file 文件
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isFile(final File file) {
        return isFileExists(file) && file.isFile();
    }

    /**
     * 判断目录是否存在,不存在则判断是否创建成功
     *
     * @param dirPath 目录路径
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsDir(final String dirPath) {
        return createOrExistsDir(getFileByPath(dirPath));
    }

    /**
     * 判断目录是否存在,不存在则判断是否创建成功
     *
     * @param file 文件
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsDir(final File file) {
        // 如果存在,是目录则返回true,是文件则返回false,不存在则返回是否创建成功
        return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
    }

    /**
     * 判断文件是否存在,不存在则判断是否创建成功
     *
     * @param filePath 文件路径
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsFile(final String filePath) {
        return createOrExistsFile(getFileByPath(filePath));
    }

    /**
     * 判断文件是否存在,不存在则判断是否创建成功
     *
     * @param file 文件
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsFile(final File file) {
        if (file == null) return false;
        // 如果存在,是文件则返回true,是目录则返回false
        if (file.exists()) return file.isFile();
        if (!createOrExistsDir(file.getParentFile())) return false;
        try {
            return file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断文件是否存在,存在则在创建之前删除
     *
     * @param file 文件
     * @return {@code true}: 创建成功<br>{@code false}: 创建失败
     */
    public static boolean createFileByDeleteOldFile(final File file) {
        if (file == null) return false;
        // 文件存在并且删除失败返回false
        if (file.exists() && !file.delete()) return false;
        // 创建目录失败返回false
        if (!createOrExistsDir(file.getParentFile())) return false;
        try {
            return file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制或移动目录
     *
     * @param srcDirPath  源目录路径
     * @param destDirPath 目标目录路径
     * @param isMove      是否移动
     * @return {@code true}: 复制或移动成功<br>{@code false}: 复制或移动失败
     */
    private static boolean copyOrMoveDir(final String srcDirPath, final String destDirPath, final boolean isMove) {
        return copyOrMoveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath), isMove);
    }

    /**
     * 复制或移动目录
     *
     * @param srcDir  源目录
     * @param destDir 目标目录
     * @param isMove  是否移动
     * @return {@code true}: 复制或移动成功<br>{@code false}: 复制或移动失败
     */
    private static boolean copyOrMoveDir(final File srcDir, final File destDir, final boolean isMove) {
        if (srcDir == null || destDir == null) return false;
        // 如果目标目录在源目录中则返回false,看不懂的话好好想想递归怎么结束
        // srcPath : F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res
        // destPath: F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res1
        // 为防止以上这种情况出现出现误判,须分别在后面加个路径分隔符
        String srcPath = srcDir.getPath() + File.separator;
        String destPath = destDir.getPath() + File.separator;
        if (destPath.contains(srcPath)) return false;
        // 源文件不存在或者不是目录则返回false
        if (!srcDir.exists() || !srcDir.isDirectory()) return false;
        // 目标目录不存在返回false
        if (!createOrExistsDir(destDir)) return false;
        File[] files = srcDir.listFiles();
        for (File file : files) {
            File oneDestFile = new File(destPath + file.getName());
            if (file.isFile()) {
                // 如果操作失败返回false
                if (!copyOrMoveFile(file, oneDestFile, isMove)) return false;
            } else if (file.isDirectory()) {
                // 如果操作失败返回false
                if (!copyOrMoveDir(file, oneDestFile, isMove)) return false;
            }
        }
        return !isMove || deleteDir(srcDir);
    }

    /**
     * 复制或移动文件
     *
     * @param srcFilePath  源文件路径
     * @param destFilePath 目标文件路径
     * @param isMove       是否移动
     * @return {@code true}: 复制或移动成功<br>{@code false}: 复制或移动失败
     */
    private static boolean copyOrMoveFile(final String srcFilePath, final String destFilePath, final boolean isMove) {
        return copyOrMoveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath), isMove);
    }

    /**
     * 复制或移动文件
     *
     * @param srcFile  源文件
     * @param destFile 目标文件
     * @param isMove   是否移动
     * @return {@code true}: 复制或移动成功<br>{@code false}: 复制或移动失败
     */
    private static boolean copyOrMoveFile(final File srcFile, final File destFile, final boolean isMove) {
        if (srcFile == null || destFile == null) return false;
        // 源文件不存在或者不是文件则返回false
        if (!srcFile.exists() || !srcFile.isFile()) return false;
        // 目标文件存在且是文件则返回false
        if (destFile.exists() && destFile.isFile()) return false;
        // 目标目录不存在返回false
        if (!createOrExistsDir(destFile.getParentFile())) return false;
        try {
            return FileIOUtils.writeFileFromIS(destFile, new FileInputStream(srcFile), false)
                    && !(isMove && !deleteFile(srcFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制目录
     *
     * @param srcDirPath  源目录路径
     * @param destDirPath 目标目录路径
     * @return {@code true}: 复制成功<br>{@code false}: 复制失败
     */
    public static boolean copyDir(final String srcDirPath, final String destDirPath) {
        return copyDir(getFileByPath(srcDirPath), getFileByPath(destDirPath));
    }

    /**
     * 复制目录
     *
     * @param srcDir  源目录
     * @param destDir 目标目录
     * @return {@code true}: 复制成功<br>{@code false}: 复制失败
     */
    public static boolean copyDir(final File srcDir, final File destDir) {
        return copyOrMoveDir(srcDir, destDir, false);
    }

    /**
     * 复制文件
     *
     * @param srcFilePath  源文件路径
     * @param destFilePath 目标文件路径
     * @return {@code true}: 复制成功<br>{@code false}: 复制失败
     */
    public static boolean copyFile(final String srcFilePath, final String destFilePath) {
        return copyFile(getFileByPath(srcFilePath), getFileByPath(destFilePath));
    }

    /**
     * 复制文件
     *
     * @param srcFile  源文件
     * @param destFile 目标文件
     * @return {@code true}: 复制成功<br>{@code false}: 复制失败
     */
    public static boolean copyFile(final File srcFile, final File destFile) {
        return copyOrMoveFile(srcFile, destFile, false);
    }

    /**
     * 移动目录
     *
     * @param srcDirPath  源目录路径
     * @param destDirPath 目标目录路径
     * @return {@code true}: 移动成功<br>{@code false}: 移动失败
     */
    public static boolean moveDir(final String srcDirPath, final String destDirPath) {
        return moveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath));
    }

    /**
     * 移动目录
     *
     * @param srcDir  源目录
     * @param destDir 目标目录
     * @return {@code true}: 移动成功<br>{@code false}: 移动失败
     */
    public static boolean moveDir(final File srcDir, final File destDir) {
        return copyOrMoveDir(srcDir, destDir, true);
    }

    /**
     * 移动文件
     *
     * @param srcFilePath  源文件路径
     * @param destFilePath 目标文件路径
     * @return {@code true}: 移动成功<br>{@code false}: 移动失败
     */
    public static boolean moveFile(final String srcFilePath, final String destFilePath) {
        Log.e("xxx","移动文件"+srcFilePath+"---->"+destFilePath);
        return moveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath));
    }

    /**
     * 移动文件
     *
     * @param srcFile  源文件
     * @param destFile 目标文件
     * @return {@code true}: 移动成功<br>{@code false}: 移动失败
     */
    public static boolean moveFile(final File srcFile, final File destFile) {
        return copyOrMoveFile(srcFile, destFile, true);
    }

    /**
     * 删除目录
     *
     * @param dirPath 目录路径
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteDir(final String dirPath) {
        return deleteDir(getFileByPath(dirPath));
    }


    /**
     * 删除文件或目录
     * @param file
     * @return
     */
    public static boolean deleteDirOrFile(File file){
        if (file == null) return false;
        if (!file.exists()) return false;
        if(file.isFile()){
            return deleteFile(file);
        }else{
            return deleteDir(file);
        }
    }

    /**
     * 删除文件或目录
     * @param path
     * @return
     */
    public static boolean deleteDirOrFile(String path){
        return deleteDirOrFile(getFileByPath(path));
    }

    /**
     * 删除目录
     *
     * @param dir 目录
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteDir(final File dir) {
        if (dir == null) return false;
        // 目录不存在返回true
        if (!dir.exists()) return true;
        // 不是目录返回false
        if (!dir.isDirectory()) return false;
        // 现在文件存在且是文件夹
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.isFile()) {
                    if (!file.delete()) return false;
                } else if (file.isDirectory()) {
                    if (!deleteDir(file)) return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 删除Luban文件集合 以“|” 分割
     * @param srcFilePaths
     */
    public static void  deleteFiles(String srcFilePaths){
        if(TextUtils.isEmpty(srcFilePaths))
            return;
        List<String> list = Arrays.asList(srcFilePaths.split("\\|"));
        for(String path : list){
            if(path.contains("luban")){
                deleteFile(path);
            }
        }
    }

    /**
     * 删除文件
     *
     * @param srcFilePath 文件路径
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteFile(final String srcFilePath) {
        return deleteFile(getFileByPath(srcFilePath));
    }

    /**
     * 删除文件
     *
     * @param file 文件
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteFile(final File file) {
        return file != null && (!file.exists() || file.isFile() && file.delete());
    }

    /**
     * 删除目录下的所有文件
     *
     * @param dirPath 目录路径
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteFilesInDir(final String dirPath) {
        return deleteFilesInDir(getFileByPath(dirPath));
    }

    /**
     * 删除目录下的所有文件
     *
     * @param dir 目录
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteFilesInDir(final File dir) {
        if (dir == null) return false;
        // 目录不存在返回true
        if (!dir.exists()) return true;
        // 不是目录返回false
        if (!dir.isDirectory()) return false;
        // 现在文件存在且是文件夹
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.isFile()) {
                    if (!file.delete()) return false;
                } else if (file.isDirectory()) {
                    if (!deleteDir(file)) return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取目录下所有文件
     *
     * @param dirPath     目录路径
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDir(final String dirPath, final boolean isRecursive) {
        return listFilesInDir(getFileByPath(dirPath), isRecursive);
    }

    /**
     * 获取目录下所有文件
     *
     * @param dir         目录
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDir(final File dir, final boolean isRecursive) {
        if (!isDir(dir)) return null;
        if (isRecursive) return listFilesInDir(dir);
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            Collections.addAll(list, files);
        }
        return list;
    }

    /**
     * 获取目录下所有文件包括子目录
     *
     * @param dirPath 目录路径
     * @return 文件链表
     */
    public static List<File> listFilesInDir(final String dirPath) {
        return listFilesInDir(getFileByPath(dirPath));
    }

    /**
     * 获取目录下所有文件包括子目录
     *
     * @param dir 目录
     * @return 文件链表
     */
    public static List<File> listFilesInDir(final File dir) {
        if (!isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                list.add(file);
                if (file.isDirectory()) {
                    List<File> fileList = listFilesInDir(file);
                    if (fileList != null) {
                        list.addAll(fileList);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 获取目录下所有后缀名为suffix的文件
     * <p>大小写忽略</p>
     *
     * @param dirPath     目录路径
     * @param suffix      后缀名
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final String dirPath, final String suffix, final boolean isRecursive) {
        return listFilesInDirWithFilter(getFileByPath(dirPath), suffix, isRecursive);
    }

    /**
     * 获取目录下所有后缀名为suffix的文件
     * <p>大小写忽略</p>
     *
     * @param dir         目录
     * @param suffix      后缀名
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final File dir, final String suffix, final boolean isRecursive) {
        if (isRecursive) return listFilesInDirWithFilter(dir, suffix);
        if (dir == null || !isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if(file.length()>10){
                    if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
                        list.add(file);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 获取目录下所有后缀名为suffix的文件包括子目录
     * <p>大小写忽略</p>
     *
     * @param dirPath 目录路径
     * @param suffix  后缀名
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final String dirPath, final String suffix) {
        return listFilesInDirWithFilter(getFileByPath(dirPath), suffix);
    }

    /**
     * 获取目录下所有后缀名为suffix的文件包括子目录
     * <p>大小写忽略</p>
     *
     * @param dir    目录
     * @param suffix 后缀名
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final File dir, final String suffix) {
        if (dir == null || !isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
                    list.add(file);
                }
                if (file.isDirectory()) {
                    list.addAll(listFilesInDirWithFilter(file, suffix));
                }
            }
        }
        return list;
    }

    /**
     * 获取目录下所有符合filter的文件
     *
     * @param dirPath     目录路径
     * @param filter      过滤器
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final String dirPath, final FilenameFilter filter, final boolean isRecursive) {
        return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive);
    }

    /**
     * 获取目录下所有符合filter的文件
     *
     * @param dir         目录
     * @param filter      过滤器
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final File dir, final FilenameFilter filter, final boolean isRecursive) {
        if (isRecursive) return listFilesInDirWithFilter(dir, filter);
        if (dir == null || !isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (filter.accept(file.getParentFile(), file.getName())) {
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 获取目录下所有符合filter的文件包括子目录
     *
     * @param dirPath 目录路径
     * @param filter  过滤器
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final String dirPath, final FilenameFilter filter) {
        return listFilesInDirWithFilter(getFileByPath(dirPath), filter);
    }

    /**
     * 获取目录下所有符合filter的文件包括子目录
     *
     * @param dir    目录
     * @param filter 过滤器
     * @return 文件链表
     */
    public static List<File> listFilesInDirWithFilter(final File dir, final FilenameFilter filter) {
        if (dir == null || !isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (filter.accept(file.getParentFile(), file.getName())) {
                    list.add(file);
                }
                if (file.isDirectory()) {
                    list.addAll(listFilesInDirWithFilter(file, filter));
                }
            }
        }
        return list;
    }

    /**
     * 获取目录下指定文件名的文件包括子目录
     * <p>大小写忽略</p>
     *
     * @param dirPath  目录路径
     * @param fileName 文件名
     * @return 文件链表
     */
    public static List<File> searchFileInDir(final String dirPath, final String fileName) {
        return searchFileInDir(getFileByPath(dirPath), fileName);
    }

    /**
     * 获取目录下指定文件名的文件包括子目录
     * <p>大小写忽略</p>
     *
     * @param dir      目录
     * @param fileName 文件名
     * @return 文件链表
     */
    public static List<File> searchFileInDir(final File dir, final String fileName) {
        if (dir == null || !isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.getName().toUpperCase().equals(fileName.toUpperCase())) {
                    list.add(file);
                }
                if (file.isDirectory()) {
                    list.addAll(searchFileInDir(file, fileName));
                }
            }
        }
        return list;
    }

    /**
     * 获取文件最后修改的毫秒时间戳
     *
     * @param filePath 文件路径
     * @return 文件最后修改的毫秒时间戳
     */
    public static long getFileLastModified(final String filePath) {
        return getFileLastModified(getFileByPath(filePath));
    }

    /**
     * 获取文件最后修改的毫秒时间戳
     *
     * @param file 文件
     * @return 文件最后修改的毫秒时间戳
     */
    public static long getFileLastModified(final File file) {
        if (file == null) return -1;
        return file.lastModified();
    }

    /**
     * 简单获取文件编码格式
     *
     * @param filePath 文件路径
     * @return 文件编码
     */
    public static String getFileCharsetSimple(final String filePath) {
        return getFileCharsetSimple(getFileByPath(filePath));
    }

    /**
     * 简单获取文件编码格式
     *
     * @param file 文件
     * @return 文件编码
     */
    public static String getFileCharsetSimple(final File file) {
        int p = 0;
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(file));
            p = (is.read() << 8) + is.read();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeIO(is);
        }
        switch (p) {
            case 0xefbb:
                return "UTF-8";
            case 0xfffe:
                return "Unicode";
            case 0xfeff:
                return "UTF-16BE";
            default:
                return "GBK";
        }
    }

    /**
     * 获取文件行数
     *
     * @param filePath 文件路径
     * @return 文件行数
     */
    public static int getFileLines(final String filePath) {
        return getFileLines(getFileByPath(filePath));
    }

    /**
     * 获取文件行数
     * <p>比readLine要快很多</p>
     *
     * @param file 文件
     * @return 文件行数
     */
    public static int getFileLines(final File file) {
        int count = 1;
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[1024];
            int readChars;
            if (LINE_SEP.endsWith("\n")) {
                while ((readChars = is.read(buffer, 0, 1024)) != -1) {
                    for (int i = 0; i < readChars; ++i) {
                        if (buffer[i] == ''\n'') ++count;
                    }
                }
            } else {
                while ((readChars = is.read(buffer, 0, 1024)) != -1) {
                    for (int i = 0; i < readChars; ++i) {
                        if (buffer[i] == ''\r'') ++count;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeIO(is);
        }
        return count;
    }

    /**
     * 获取目录大小
     *
     * @param dirPath 目录路径
     * @return 文件大小
     */
    public static String getDirSize(final String dirPath) {
        return getDirSize(getFileByPath(dirPath));
    }

    /**
     * 获取目录大小
     *
     * @param dir 目录
     * @return 文件大小
     */
    public static String getDirSize(final File dir) {
        long len = getDirLength(dir);
        return len == -1 ? "" : byte2FitMemorySize(len);
    }

    /**
     * 获取文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    public static String getFileSize(final String filePath) {
        return getFileSize(getFileByPath(filePath));
    }

    /**
     * 获取文件大小
     *
     * @param file 文件
     * @return 文件大小
     */
    public static String getFileSize(final File file) {
        long len = getFileLength(file);
        return len == -1 ? "" : byte2FitMemorySize(len);
    }

    /**
     * 获取目录长度
     *
     * @param dirPath 目录路径
     * @return 目录长度
     */
    public static long getDirLength(final String dirPath) {
        return getDirLength(getFileByPath(dirPath));
    }

    /**
     * 获取目录长度
     *
     * @param dir 目录
     * @return 目录长度
     */
    public static long getDirLength(final File dir) {
        if (!isDir(dir)) return -1;
        long len = 0;
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.isDirectory()) {
                    len += getDirLength(file);
                } else {
                    len += file.length();
                }
            }
        }
        return len;
    }

    /**
     * 获取文件长度
     *
     * @param filePath 文件路径
     * @return 文件长度
     */
    public static long getFileLength(final String filePath) {
        return getFileLength(getFileByPath(filePath));
    }

    /**
     * 获取文件长度
     *
     * @param file 文件
     * @return 文件长度
     */
    public static long getFileLength(final File file) {
        if (!isFile(file)) return -1;
        return file.length();
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param filePath 文件路径
     * @return 文件的MD5校验码
     */
    public static String getFileMD5ToString(final String filePath) {
        File file = isSpace(filePath) ? null : new File(filePath);
        return getFileMD5ToString(file);
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param filePath 文件路径
     * @return 文件的MD5校验码
     */
    public static byte[] getFileMD5(final String filePath) {
        File file = isSpace(filePath) ? null : new File(filePath);
        return getFileMD5(file);
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param file 文件
     * @return 文件的MD5校验码
     */
    public static String getFileMD5ToString(final File file) {
        return bytes2HexString(getFileMD5(file));
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param file 文件
     * @return 文件的MD5校验码
     */
    public static byte[] getFileMD5(final File file) {
        if (file == null) return null;
        DigestInputStream dis = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            MessageDigest md = MessageDigest.getInstance("MD5");
            dis = new DigestInputStream(fis, md);
            byte[] buffer = new byte[1024 * 256];
            while (true) {
                if (!(dis.read(buffer) > 0)) break;
            }
            md = dis.getMessageDigest();
            return md.digest();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeIO(dis);
        }
        return null;
    }

    /**
     * 获取全路径中的最长目录
     *
     * @param file 文件
     * @return filePath最长目录
     */
    public static String getDirName(final File file) {
        if (file == null) return null;
        return getDirName(file.getPath());
    }

    /**
     * 获取全路径中的最长目录
     *
     * @param filePath 文件路径
     * @return filePath最长目录
     */
    public static String getDirName(final String filePath) {
        if (isSpace(filePath)) return filePath;
        int lastSep = filePath.lastIndexOf(File.separator);
        return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1);
    }

    /**
     * 获取全路径中的文件名
     *
     * @param file 文件
     * @return 文件名
     */
    public static String getFileName(final File file) {
        if (file == null) return null;
        return getFileName(file.getPath());
    }

    /**
     * 获取全路径中的文件名
     *
     * @param filePath 文件路径
     * @return 文件名
     */
    public static String getFileName(final String filePath) {
        if (isSpace(filePath)) return filePath;
        int lastSep = filePath.lastIndexOf(File.separator);
        return lastSep == -1 ? filePath : filePath.substring(lastSep + 1);
    }

    /**
     * 获取全路径中的不带拓展名的文件名
     *
     * @param file 文件
     * @return 不带拓展名的文件名
     */
    public static String getFileNameNoExtension(final File file) {
        if (file == null) return null;
        return getFileNameNoExtension(file.getPath());
    }

    /**
     * 获取全路径中的不带拓展名的文件名
     *
     * @param filePath 文件路径
     * @return 不带拓展名的文件名
     */
    public static String getFileNameNoExtension(final String filePath) {
        if (isSpace(filePath)) return filePath;
        int lastPoi = filePath.lastIndexOf(''.'');
        int lastSep = filePath.lastIndexOf(File.separator);
        if (lastSep == -1) {
            return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi));
        }
        if (lastPoi == -1 || lastSep > lastPoi) {
            return filePath.substring(lastSep + 1);
        }
        return filePath.substring(lastSep + 1, lastPoi);
    }

    /**
     * 获取全路径中的文件拓展名
     *
     * @param file 文件
     * @return 文件拓展名
     */
    public static String getFileExtension(final File file) {
        if (file == null) return null;
        return getFileExtension(file.getPath());
    }

    /**
     * 获取全路径中的文件拓展名
     *
     * @param filePath 文件路径
     * @return 文件拓展名
     */
    public static String getFileExtension(final String filePath) {
        if (isSpace(filePath)) return filePath;
        int lastPoi = filePath.lastIndexOf(''.'');
        int lastSep = filePath.lastIndexOf(File.separator);
        if (lastPoi == -1 || lastSep >= lastPoi) return "";
        return filePath.substring(lastPoi + 1);
    }
    /**
     * 根据文件类型去删除其在系统中对应的Media数据库
     * @param file
     * @return -1代表不是媒体文件,0表示在数据库中查找不到,1找到数据库中对应的数据,并且删除
     */
    public static int deleteMedia(File file){
        String name = file.getName();
        String path = file.getAbsolutePath();
        if(name.contains(".jpg") || name.contains(".mp4")){
            Uri MEDIA_URI = null;
            if(name.contains(".jpg")){
                if(path.contains("mnt/sdcard/")){
                    MEDIA_URI = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
                    path = path.replace("/mnt/sdcard/", "/storage/sdcard0/");
                }else if(file.getAbsolutePath().contains("mnt/sdcard2/")){
                    MEDIA_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    path = path.replace("/mnt/sdcard2/","/storage/sdcard1/");
                }
            }else{
                if(path.contains("mnt/sdcard/")){
                    MEDIA_URI = MediaStore.Video.Media.INTERNAL_CONTENT_URI;
                    path = path.replace("/mnt/sdcard1/","/storage/sdcard0/");
                }else if(file.getAbsolutePath().contains("mnt/sdcard2/")){
                    MEDIA_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    path = path.replace("/mnt/sdcard2/","/storage/sdcard1/");
                }
            }
            int resultCode = 0 ;
            // resultCode = MyApp.getInstance().getContentResolver().delete(MEDIA_URI, MediaStore.Images.Media.DATA+"="+"''"+path+"''" , null);
            return resultCode;
        }else{
            return -1;
        }
    }
    ///////////////////////////////////////////////////////////////////////////
    // copy from ConvertUtils
    ///////////////////////////////////////////////////////////////////////////

    private static final char hexDigits[] = {''0'', ''1'', ''2'', ''3'', ''4'', ''5'', ''6'', ''7'', ''8'', ''9'', ''A'', ''B'', ''C'', ''D'', ''E'', ''F''};

    /**
     * byteArr转hexString
     * <p>例如:</p>
     * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8
     *
     * @param bytes 字节数组
     * @return 16进制大写字符串
     */
    private static String bytes2HexString(final byte[] bytes) {
        if (bytes == null) return null;
        int len = bytes.length;
        if (len <= 0) return null;
        char[] ret = new char[len << 1];
        for (int i = 0, j = 0; i < len; i++) {
            ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
            ret[j++] = hexDigits[bytes[i] & 0x0f];
        }
        return new String(ret);
    }

    /**
     * 字节数转合适内存大小
     * <p>保留3位小数</p>
     *
     * @param byteNum 字节数
     * @return 合适内存大小
     */
    @SuppressLint("DefaultLocale")
    private static String byte2FitMemorySize(final long byteNum) {
        if (byteNum < 0) {
            return "shouldn''t be less than zero!";
        } else if (byteNum < 1024) {
            return String.format("%.3fB", (double) byteNum + 0.0005);
        } else if (byteNum < 1048576) {
            return String.format("%.3fKB", (double) byteNum / 1024 + 0.0005);
        } else if (byteNum < 1073741824) {
            return String.format("%.3fMB", (double) byteNum / 1048576 + 0.0005);
        } else {
            return String.format("%.3fGB", (double) byteNum / 1073741824 + 0.0005);
        }
    }

    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    // ---------------

    /**
     * 在指定的位置创建指定的文件
     * @param filePath 完整的文件路径
     * @param mkdir 是否创建相关的文件夹
     * @throws IOException
     */
    public static void mkFile(String filePath, boolean mkdir) throws IOException{
        File file = new File(filePath);
        /**
         * mkdirs()创建多层目录,mkdir()创建单层目录
         * writeObject时才创建磁盘文件。
         * 若不创建文件,readObject出错。
         */
        file.getParentFile().mkdirs();
        file.createNewFile();
        file = null;
    }

    /**
     * 在指定的位置创建文件夹
     * @param dirPath 文件夹路径
     * @return 若创建成功,则返回True;反之,则返回False
     */
    public static boolean mkDir(String dirPath) {
        return new File(dirPath).mkdirs();
    }

    /**
     * 删除指定的文件
     * @param filePath 文件路径
     * @return 若删除成功,则返回True;反之,则返回False
     */
    public static boolean delFile(String filePath) {
        return new File(filePath).delete();
    }

    /**
     * 删除指定的文件夹
     * @param dirPath 文件夹路径
     * @param delFile 文件夹中是否包含文件
     * @return 若删除成功,则返回True;反之,则返回False
     */
    public static boolean delDir(String dirPath, boolean delFile) {
        if (delFile) {
            File file = new File(dirPath);
            if (file.isFile()) {
                return file.delete();
            } else if (file.isDirectory()) {
                if (file.listFiles().length == 0) {
                    return file.delete();
                } else {
                    int zFiles = file.listFiles().length;
                    File[] delfile = file.listFiles();
                    for (int i = 0; i < zFiles; i++) {
                        if (delfile[i].isDirectory()) {
                            delDir(delfile[i].getAbsolutePath(), true);
                        }
                        delfile[i].delete();
                    }
                    return file.delete();
                }
            } else {
                return false;
            }
        } else {
            return new File(dirPath).delete();
        }
    }

    /**
     * 复制文件/文件夹 若要进行文件夹复制,请勿将目标文件夹置于源文件夹中
     * @param source 源文件(夹)
     * @param target 目标文件(夹)
     * @param isFolder 若进行文件夹复制,则为True;反之为False
     * @throws IOException
     */
    public static void copy(String source, String target, boolean isFolder) throws IOException{
        if (isFolder) {
            new File(target).mkdirs();
            File a = new File(source);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (source.endsWith(File.separator)) {
                    temp = new File(source + file[i]);
                } else {
                    temp = new File(source + File.separator + file[i]);
                }
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(target + File.separator + temp.getName().toString());
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } if (temp.isDirectory()) {
                    copy(source + File.separator + file[i], target + File.separator + file[i], true);
                }
            }
        } else {
            int byteread = 0;
            File oldfile = new File(source);
            if (oldfile.exists()) {
                InputStream inputStream = new FileInputStream(source);
                File file = new File(target);
                file.getParentFile().mkdirs();
                file.createNewFile();
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                while ((byteread = inputStream.read(buffer)) != -1){
                    outputStream.write(buffer, 0, byteread);
                }
                inputStream.close();
                outputStream.close();
            }
        }
    }

}

 

cocos2d::CCFileUtils::sharedFileUtils()->getFileData(szFile,

cocos2d::CCFileUtils::sharedFileUtils()->getFileData(szFile, "r", &bufferSize) 不同平台返回值不一样

string pathKey = CCFileUtils::sharedFileUtils()->fullPathForFilename(fileName);
    unsigned char* pBuffer = NULL;
    unsigned long bufferSize = 0;
    pBuffer = CCFileUtils::sharedFileUtils()->getFileData(pathKey.c_str(),"rb",&bufferSize);


我在使用CCFileUtils::sharedFileUtils()->getFileData(szFile,"r",&bufferSize) 读取一个csv文件时,发现win32平台比其它平台得到的值有时要小。

原因是:CCFileUtils::getFileData(szFile,&bufferSize)对于一个文本文件(以\r\n换行的)

在win32下运行得到的文件尺寸小一些,似乎\r都被删除了,可是os下得到完整尺寸


如今仅仅能用二进制方式读取文本文件,确保各平台下运行效果全然同样。

cocos2d::CCFileUtils::getFileData(szFile,"rb",&bufferSize);

cocos2dx CCFileUtils::sharedFileUtils() 静态调用

cocos2dx CCFileUtils::sharedFileUtils() 静态调用

如题

CCFileUtils::sharedFileUtils()

静态调用,也就是在cpp文件的函数外面调用

Android平台会无故崩溃,跟踪调试发现在CCFileUtilsAndroid.cpp的42行过不去即

CCFileUtils* CCFileUtils::sharedFileUtils()
{
    if (s_sharedFileUtils == NULL)
    {
        s_sharedFileUtils = new CCFileUtilsAndroid();
        s_sharedFileUtils->init();
        std::string resourcePath = getApkPath();
        s_pZipFile = new ZipFile(resourcePath,"assets/");
    }
    return s_sharedFileUtils;
}
std::string resourcePath = getApkPath();

这行 然后查看getApkPath()函数,里面也就返回string g_apkPath的c_str()

最后没查出别的有用信息,不过此时g_apkPath应该是null,因为g_apkPath是依靠java那边回调才设置的值

JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetApkPath(jnienv*  env,jobject thiz,jstring apkPath) {
        g_apkPath = JniHelper::jstring2string(apkPath);
    }

而静态调用了CCFileUtils::sharedFileUtils(),发生在静态区

而java加载libgame.so的方法如下

static {
		System.loadLibrary("game");
	}
可想而知getApkPath的调用就会在nativeSetApkPath之前

所以sharedFileUtils()就不要在全局区调用了(也就是静态调用)


但是ios平台,是没有问题



ps:遇到问题就先记录,以免以后再次遇到,耗费时间去找问题

我们今天的关于RedisSingleUtils 工具类redisutils工具类方法的分享就到这里,谢谢您的阅读,如果想了解更多关于15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)、Android-FileUtils-工具类、cocos2d::CCFileUtils::sharedFileUtils()->getFileData(szFile, "r", &bufferSize) 不同平台返回值不一样、cocos2dx CCFileUtils::sharedFileUtils() 静态调用的相关信息,可以在本站进行搜索。

本文标签:

上一篇[Docker] VMware CentOS7 中的 docker 安装(vmware安装docker步骤)

下一篇已解决:Elasticsearch 报错:exception [type=search_phase_execution_exception, reason=all shards failed]