• FileOperation源码


    package com.citic.util.comm;
    
    import java.io.*;
    import java.nio.channels.FileLock;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Scanner;
    
    import com.citic.util.comm.*;
    import com.citic.util.MD5Util;
    import com.citic.util.XMLUtil;
    import com.sun.org.apache.xml.internal.serialize.LineSeparator;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    public class FileOperation implements IConstants{
        private static int debuglevel=0;//基础方法禁止使用config中的debuglevel,此处使用此变量仅为了统一使用方法
        public static void propertity2File(String srcfile, String desfile) {
            InputStream in=null;
            BufferedInputStream input=null;
            BufferedOutputStream output=null;
            CommFun.log(debuglevel, srcfile);
            try {
                if (new File(desfile).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;
                    }
                }
                in = FileOperation.class.getResourceAsStream(srcfile);
                input = new BufferedInputStream(in);
                System.out.println("input.ava:"+input.available());
                output=new BufferedOutputStream(new FileOutputStream(desfile));
                int r;
                byte[] bytes=new byte[1024];
                while((r=input.read(bytes))!=-1){
                    output.write(bytes, 0, r);
                    CommFun.log(debuglevel,"input:"+r);
                }
                output.flush();
                CommFun.log(debuglevel,desfile + "config file is created!");
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                    if (in != null)
                        in.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        
        public static void propertity2File1(String srcfile, String desfile) {
            InputStreamReader reader=null;
            //FileReader reader=null;
            BufferedReader breader=null;
            CommFun.log(debuglevel, srcfile);
            try {
                if (new File(desfile).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;
                    }
                }
                reader=new InputStreamReader(FileOperation.class.getResourceAsStream(srcfile),"Unicode");
                breader=new BufferedReader(reader);
                String tmps=null;
                while((tmps=breader.readLine())!=null){
                    System.out.println(tmps);
                }
                CommFun.log(debuglevel,desfile + "config file is created!");
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
    //            try {
    //                if (output != null)
    //                    output.close();
    //                if (input != null)
    //                    input.close();
    //                if (reader != null)
    //                    reader.close();
    //            } catch (Exception e) {
    //                throw new RuntimeException(e);
    //            }
            }
        }
        
        /**
         * 获取配置文件的排它锁,实现单进程使用
         * @return
         */
        public static boolean getlock(){
            String file = System.getProperty("user.dir").trim() + File.separator
            + config+".lck";
            boolean lockflag=true;
    //        FileLock lck = null;
    //        try {
    //            FileOutputStream fos=new FileOutputStream(file);
    //            lck = fos.getChannel().tryLock();
    //            CommFun.log(INFO, "对文件加锁成功[" + file + "]");
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //            throw new RuntimeException();
    //        }
    //        return lck == null ? false : true;
            
            File flagFile=new File(file);
            try {
                if(false==flagFile.createNewFile()){
                    lockflag=false;
                }
            } catch (IOException e) {
                lockflag=false;
                e.printStackTrace();
            }
            flagFile.deleteOnExit();
            return lockflag;
        }
        
        /**
         * StringBuffer[]数组写入到指定文件
         * 
         * @param stb
         * @param filename
         */
        public static void stringbuffer2file(StringBuffer[] stb, String filename){
            stringbuffer2file(stb,filename,null);
        }
        
        /**
         * @param stb
         * @param filename
         * @param strmd5
         * 加入传入的strmd5,因计算后的值不一样,所以直接传入吧,MQUtil.java中
         */
        public static void stringbuffer2file(StringBuffer[] stb, String filename,String strmd5) {
            try {
                String pthseparator = System.getProperty("file.separator");
                // filename = filename.replace("/", "\");
                String localpth=filename.substring(0,filename.lastIndexOf(pthseparator));
                CommFun.log(localpth);
                File f = new File(localpth);
                if (!f.exists()) {
                    f.mkdir();
                }
    //            FileWriter fw = new FileWriter(filename,true);
    //            for (int i = 0; i < stb.length && stb[i] != null; i++) {
    //                fw.write(stb[i].toString() + "
    ");
    //            }
    //            fw.flush();
    //            fw.close();
    
                StringBuffer tmpstr1 = new StringBuffer();
                for (int i = 0; i < stb.length && stb[i] != null; i++) {
                    tmpstr1.append(stb[i]).append(System.getProperty("line.separator"));
                }
                
                //对于xml文件走XML创建方法,否则使用一般文件创建 20170901 张明伟
                //新增方法和判断
                if(filename.matches(".*\.xml")){
                    XMLUtil.xmlCreate(tmpstr1.toString(), filename);    
                }else{
                    writeFile(tmpstr1.toString(), filename);
                }
                
                tmpstr1=null;
                if(!(new File(filename).length()>0)){
                    CommFun.log(INFO, "写入文件"+filename+"失败或无数据!");
                    return;
                }
                CommFun.log(INFO, "写入文件"+filename+"成功!");
                if(strmd5!=null && !"".equals(strmd5) && ConfigFileUtil.getValue("md5")=="true"){
                    String filemd5=MD5Util.getMD5String(filename);
                    String tmpstr="filename:"+filename+",strmd5:"+strmd5+",filemd5:"+filemd5;
                    CommFun.log(tmpstr);
                    String md5file=localpth+File.separator+"MD5.txt";
                    writeFile(tmpstr,md5file);
                }
            } catch (Exception e) {
                CommFun.log(ERR, "写入文件"+filename+"失败!");
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 一般文件写入
         * @param tmpstr
         * @param filename
         */
        public static void writeFile(String tmpstr,String filename){
            try{
                FileWriter fw1 = new FileWriter(filename,true);
                fw1.write(tmpstr + "
    ");
                fw1.flush();
                fw1.close();
                CommFun.log(debuglevel,"写入"+filename+"成功!");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        
        
        public static String GetImageStr(String imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    //        String imgFile = "d:\01.jpg";// 待处理的图片
            InputStream in = null;
            byte[] data = null;
            // 读取图片字节数组
            try {
                File fl = new File(imgFile);
                CommFun.log(debuglevel,fl.getName());
                in = new FileInputStream(imgFile);
    
                data = new byte[in.available()];
                in.read(data);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);// 返回Base64编码过的字节数组字符串
        }
    
        public static boolean GenerateImage(String imgStr,String filename) {// 对字节数组字符串进行Base64解码并生成图片
            if (imgStr == null) // 图像数据为空
                return false;
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                // Base64解码
                byte[] b = decoder.decodeBuffer(imgStr);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }
                SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                Date dt=new Date();
                // 生成jpeg图片
                String imgFilePath = filename+"_"+ft.format(dt);// 新生成的图片
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        
        public static HashMap<String, String> loadMD5txt(String path) {
            HashMap<String, String> md5map = new HashMap<String, String>();
            String md5file = path + File.separator + md5filename;
            CommFun.log(debuglevel, "MD5文件:" + md5file);
            if (new File(md5file).exists()) {
                CommFun.log(debuglevel, "MD5文件存在," + md5file);
                try {
                    BufferedReader bufferreader = new BufferedReader(
                            new FileReader(md5file));
                    String fline;
                    while ((fline = bufferreader.readLine()) != null) {
                        if (!"".equals(fline) && fline != null) {
                            md5map.put(fline.split(",")[1].split(":")[1], "");
                        }
                    }
                    CommFun.log("共载入MD5[" + md5map.size() + "]条记录");
                    // CommFun.log(debuglevel,""+md5map);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return md5map;
        }
        
    }
    View Code
  • 相关阅读:
    [SharePoint 2010] 自定义字段类型开发(二)
    [SharePoint 2007/2010]Query SharePoint Calendar Event
    打印出带颜色的调试信息
    c语言调试开关
    c语言调试接口
    字符串截取
    黑客
    【原创】洛谷 LUOGU P3379 【模板】最近公共祖先(LCA) -> 倍增
    【转载】从头到尾彻底理解KMP
    【原创】tarjan算法初步(强连通子图缩点)
  • 原文地址:https://www.cnblogs.com/silencemaker/p/12632178.html
Copyright © 2020-2023  润新知