• ConfigFileUtil读写操作


    package com.citic.util.comm;
    
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.Map.Entry;
    
    import com.citic.util.comm.*;
    
    public class ConfigFileUtil implements IConstants{
        private String dataFilepath;
        private static Properties property;
        private static File flname;
        private static File dflname;
        private static Map<String, String> hm = new LinkedHashMap<String, String>();
        private static ConfigFileUtil cfgu;
        /******************************/
        //只能使用0,不能改为其它,请注意,否则
        //,则会和CommFun中的调用形成循环,此两个基础过程慎改
        //张明伟 20170518
        private static final int debuglevel=0;
        /******************************/
        /*
         * 由于暂时未实现对数据
         * 如果当前目录未有配置文件数据,则直接在当前目录下生成
         * 此类中要防止方法嵌套调用
         */
        private ConfigFileUtil(){
            if (0 == hm.size()) {
                InputStream in=null;
                String fl = File.separator+config;
                String destfile = System.getProperty("user.dir").trim() + fl;
                String srcfile ;//= (this.getClass().getResource(File.separator).getPath() + fl).substring(1);
    //            srcfile = (this.getClass().getResource("/").getPath()+fl).substring(1);
                srcfile = ClassLoader.class.getResource("/"+config).getPath();
                System.out.println("destfile is [" + destfile+ "] and 
    srcfile is [" + srcfile + "]");
                CommFun.log(debuglevel, "destfile is [" + destfile
                        + "] and 
    srcfile is [" + srcfile + "]");
                flname = new File(srcfile);
                dflname = new File(destfile);
                CommFun.log(debuglevel,"flname " + flname.getPath() + "");
                CommFun.log(debuglevel,"flname " + flname.length() + "");
                // 如果项目下文件不存丰或者文件少于120字节或者项目下文件创建时间比原文件晚,需要重新拷贝
                try {
                    System.out.println(flname.length());
                    System.out.println(dflname.length());
                    System.out.println(dflname.exists());
                    System.out.println(new Date(flname.lastModified()));
                    System.out.println(new Date(dflname.lastModified()));
                    boolean needcrtflag=false;
                    if (!dflname.exists() || dflname.length() < 120
                            || flname.lastModified() > dflname.lastModified()) {
    //                    in = this.getClass().getResourceAsStream("/"+configfile);
                        in = ConfigFileUtil.class.getClass().getResourceAsStream("/"+config);
                        FileOperation.propertity2File("/"+config,destfile);
                        needcrtflag=true;
                        CommFun.log(debuglevel,dflname + "is need to create!config file is created!");
                        System.out.println(dflname + "is need to create!config file is created!");
                    } else {
                        in = new FileInputStream(System.getProperty("user.dir")+ fl);
                        CommFun.log(debuglevel,""+in+","+in.available());
                        CommFun.log(debuglevel,dflname + "is exists!read from local directory!");
                    }
                    property = new Properties();
                    property.load(in);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally{
                    try {
                        if(in!=null){
                            in.close();    
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                Iterator itr = property.entrySet().iterator();
                while (itr.hasNext()) {
                    Entry e = (Entry) itr.next();
                    hm.put(e.getKey().toString().toUpperCase(), e.getValue()
                            .toString());
                }
                // hm.put("dataFilepath", getPath());
                hm.put("osName", System.getProperty("os.name").toLowerCase());
            }
        }
        
        public static synchronized ConfigFileUtil getInstance(){
            if(cfgu==null){
                cfgu=new ConfigFileUtil();
            }
            return cfgu;
        }
    
        public static String getValue(String key) {
            if (0 == hm.size()) {
                getInstance();
            }
            String vlu = hm.get(key.toUpperCase());
            if(vlu == null || "".equals(vlu)){
                CommFun.log(debuglevel, "配置表中不存在键值为["+key+"]的配置,请检查!");
                //System.out.println("配置表中不存在键值为["+key+"]的配置,请检查!");
            }
            
            try{
                int commentpos=0;
                commentpos=vlu.indexOf("#");
                vlu=vlu.substring(0, commentpos).trim();
            }catch(Exception e){
            }
            return vlu == null || "".equals(vlu) ? "" : vlu;
        }
    
        /**
         * 设置值的时间不区分大小写
         * @param key
         * @param value
         */
        public static void setValue(String key,String value) {
            if (0 == hm.size()) {
                getInstance();
            }
            if(hm.containsKey(key.toUpperCase())){
                hm.remove(key.toUpperCase());
            }
            hm.put(key.toUpperCase(), value);
            CommFun.log(debuglevel, "key:["+key+"],value:["+getValue(key)+"]");
        }
        
        public String[] getValues() {
            String[] vlus = new String[hm.size()];
            Iterator itr = hm.entrySet().iterator();
            for (int i = 0; itr.hasNext(); i++) {
                Entry e = (Entry) itr.next();
                vlus[i] = e.getKey().toString() + "=" + e.getValue().toString();
            }
            return vlus;
        }
    
        public String getPathName() {
            return getPathName(null);
        }
    
        public String getPathName(String dataDate) {
            try {
                String td;
                if ("".equals(dataDate) || dataDate == null) {
                    td = new SimpleDateFormat("yyyyMMdd").format(new Date());
                } else {
                    td = dataDate;
                }
                String osName = System.getProperty("os.name").toLowerCase();
                if (osName.startsWith("win")) {
                    dataFilepath = getValue("DFILEPATH_WIN");
                } else {
                    dataFilepath = getValue("DFILEPATH_LIN");
                }
                if("".equals(dataFilepath)||dataFilepath==null){
                    //CommFunN.log(1, "路径"+dataFilepath+"不存在,请检查配置文件中!");
                    System.out.println("路径"+dataFilepath+"不存在,请检查配置文件中!");
                }
                //CommFunN.log(1, dataFilepath);
                dataFilepath += dataFilepath.lastIndexOf(File.separator)
                        - dataFilepath.length() != 0 ? File.separator : "";
                File fdir = new File(dataFilepath + td + File.separator);
                if (fdir != null && !fdir.exists()) {
                    fdir.mkdirs();
                }
                dataFilepath = dataFilepath + td + File.separator;
                //CommFunN.log(dataFilepath);
                return dataFilepath;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        
        public void initConfigfile1() {
            String fl = config;
            File f = new File(fl);
            FileWriter fw = null;
            try {
                if (f.exists()) {
                    System.out.print("配置文件已存在,是否覆盖?(y/n)");
                    Scanner scanner = new Scanner(System.in);
                    String str = scanner.nextLine().toUpperCase();
                    System.out.println("str is [" + str + "]");
                    if ("".equals(str) || str == null || "N".equals(str)) {
                        return;
                    }
                }
                ConfigFileUtil cfg = new ConfigFileUtil();
                int len = (cfg.getValues()).length;
                System.out.println("len is [" + len + "]");
                String tmpstr = null;
                if (len < 3) {
                    return;
                }
                fw = new FileWriter(f);
                for (int i = 0; i < len; i++) {
                    tmpstr = cfg.getValues()[i].toString();
                    fw.write(tmpstr, 0, tmpstr.length());
                    fw.write("
    ");
                }
                fw.write("#"
                        + new SimpleDateFormat("yyyy年MM月dd日 HH时mm分SS秒")
                                .format(new Date()) + "写入");
                fw.flush();
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    View Code
  • 相关阅读:
    输入输出重定向
    进程管理
    普通变量_环境变量_环境变量配置文件
    高级文件操作命令_文件查找
    软件包管理_rpm命令管理_yum工具管理_文件归档压缩_源码包管理
    用户管理_组管理_设置主机名_UGO_文件高级权限_ACL权限
    字符串是否包含中文
    SQL 优化
    JS数组
    RedisUtil 工具类
  • 原文地址:https://www.cnblogs.com/silencemaker/p/12632189.html
Copyright © 2020-2023  润新知