关于文件处理,对象的复制——方法源码



一、文件处理函数库

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LuoFileUtils {
    /**
     * 下载文件
     * @throws FileNotFoundException 
     */
    public static void downFile(HttpServletRequest request, 
        HttpServletResponse response,String fileName) throws FileNotFoundException{
        String filePath = request.getSession().getServletContext().getRealPath("/") 
                          + "template/" +  fileName;  //需要下载的文件路径
        // 读到流中
        InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename="" + fileName + """);
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
            response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }

    /** 
     * @date: 2015年12月15日 上午10:12:21 
     * @description: 创建文件目录,若路径存在,就不生成 
     * @parameter:  
     * @return:  
    **/
    public static void createDocDir(String dirName) {  
        File file = new File(dirName);  
        if (!file.exists()) {  
            file.mkdirs();  
        }  
    }  

    /** 
     * @date: 2015年12月15日 上午10:12:21 
     * @description: 本地,在指定路径生成文件。若文件存在,则删除后重建。
     * @parameter:  
     * @return:  
    **/
    public static void isExistsMkDir(String dirName){  
        File file = new File(dirName);  
        if (!file.exists()) {  
            file.mkdirs();  
        }  
    } 

    /** 
     * @date: 2015年12月15日 上午10:15:14 
     * @description: 创建新文件,若文件存在则删除再创建,若不存在则直接创建
     * @parameter:  
     * @return:  
    **/
    public static void creatFileByName(File file){  
        try {  
            if (file.exists()) {  
                file.delete();  
                //发现同名文件:{},先执行删除,再新建。
            }  
            file.createNewFile();  
            //创建文件
        }  
        catch (IOException e) {  
           //创建文件失败
           throw e;
        }  
    }  
}

二、对象的复制

使用场景:在我们的实际开发当中,经常会遇到这样的情况,一个对象A有几十个属性,对象B包含了对象A所有的属性(属性名称是一样的),对象B还多出那么几个A没有的属性。但是希望把A对象的属性值全部都set进B里面。如果不断的set,get会显得很繁琐。下面就是对象复制的代码(依赖spring):

经过开发事实证明,确实如此,有时候真的会set,get很多内容,太过于繁琐,不如一个对象复制来的简单高效;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

public abstract class CopyObjectUtils extends org.springframework.beans.BeanUtils {
    public static void copyProperties(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object srcValue = readMethod.invoke(source);
                        if(srcValue == null){
                            continue;
                        }
                        Object value=srcValue;
                        //转换Double 与 BigDecimal
                        if(sourcePd.getPropertyType().isAssignableFrom( Double.class) && targetPd.getPropertyType().isAssignableFrom(BigDecimal.class)){
                            value = new BigDecimal((Double)srcValue);
                        }
                        if(sourcePd.getPropertyType().isAssignableFrom( BigDecimal.class) && targetPd.getPropertyType().isAssignableFrom(Double.class)){
                            value = ((BigDecimal)srcValue).doubleValue();
                        }
                        //转换Long 与 BigDecimal
                        if(sourcePd.getPropertyType().isAssignableFrom( Long.class) && targetPd.getPropertyType().isAssignableFrom(BigDecimal.class)){
                            value = new BigDecimal((Long)srcValue);
                        }
                        if(sourcePd.getPropertyType().isAssignableFrom( BigDecimal.class) && targetPd.getPropertyType().isAssignableFrom(Long.class)){
                            value = ((BigDecimal)srcValue).longValue();
                        }
                        //转换String为数字的 与 BigDecimal
                        if(sourcePd.getPropertyType().isAssignableFrom( String.class) && targetPd.getPropertyType().isAssignableFrom(BigDecimal.class)){
                            String srcValueStr = (String)srcValue;
                            if(srcValueStr.matches("^(([1-9]{1}\d*)|([0]{1}))(\.(\d){2})$")){
                                value = new BigDecimal((String)srcValue);
                            }
                        }

                        // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                        if (value != null) {
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }
}



原文链接地址Java我的高效编程之常用函数

原文地址:https://www.cnblogs.com/aixing/p/13327548.html