bean序列化到文件以及从文件取得被序列化的bean的方法

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Caaaa {

 /**
  * 从properties配置文件中取得被序列化的bean
  *
  * @param request
  * @param cName
  * @return
  */
 public static Object getBeanFromcookie(HttpServletRequest request,
   String cName) {
  String cookieValue = readValue(request, cName);
  Object result = new Object();

  if (cookieValue == null || "".equals(cookieValue)) {
   return result;
  }

  try {
   String decoderCookieValue = java.net.URLDecoder.decode(cookieValue,
     "UTF-8");
   ByteArrayInputStream bais = new ByteArrayInputStream(
     decoderCookieValue.getBytes("ISO-8859-1"));
   ObjectInputStream ios = new ObjectInputStream(bais);
   result = (Object) ios.readObject();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }

  return result;
 }

 /**
  * bean序列化后保存到properties配置文件中
  *
  * @param bean
  * @param response
  * @param saveSearchBeanName
  * @param request
  */
 public static void saveBeanToCookie(Object bean,
   HttpServletResponse response, String saveSearchBeanName,
   HttpServletRequest request) {
  try {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ObjectOutputStream oos = new ObjectOutputStream(baos);
   oos.writeObject(bean);
   String cookieValue = baos.toString("ISO-8859-1");
   String encodedCookieValue = java.net.URLEncoder.encode(cookieValue,
     "UTF-8");
   setCookie(response, saveSearchBeanName, encodedCookieValue, request);

  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 /**
  * 根据key读取value
  *
  * @param request
  * @param key
  * @return
  */
 public static String readValue(HttpServletRequest request, String key) {
  Properties props = new Properties();

  StringBuffer fileName = getFile(request);

  try {
   InputStream in = new BufferedInputStream(new FileInputStream(
     fileName.toString()));
   props.load(in);
   String value = props.getProperty(key);
   return value;
  } catch (IOException e) {
   e.printStackTrace();
   return null;
  }
 }

 /**
  * 取得文件名
  *
  * @param request
  * @return
  */
 public static StringBuffer getFile(HttpServletRequest request) {

  StringBuffer fileName = new StringBuffer(request.getSession()
    .getServletContext().getRealPath("/"));
  fileName.append("/xxxx/xxxx.properties");

  File file = new File(fileName.toString());
  if (!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  return fileName;
 }

 /**
  * 设置cookie
  *
  * @param response
  * @param cName
  * @param cValue
  */
 public static void setCookie(HttpServletResponse response, String cName,
   String cValue, HttpServletRequest request) {

  StringBuffer fileName = getFile(request);

  writeProperties(fileName.toString(), cName, cValue);
 }

 /**
  * 写入properties信息
  *
  * @param filePath
  * @param parameterName
  * @param parameterValue
  */
 public static void writeProperties(String filePath, String parameterName,
   String parameterValue) {
  Properties prop = new Properties();
  try {
   InputStream fis = new FileInputStream(filePath);
   // 从输入流中读取属性列表(键和元素对)
   prop.load(fis);
   // 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
   // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
   OutputStream fos = new FileOutputStream(filePath);
   prop.setProperty(parameterName, parameterValue);
   // 以适合使用 load 方法加载到 Properties 表中的格式,
   // 将此 Properties 表中的属性列表(键和元素对)写入输出流
   prop.store(fos, "Update '" + parameterName + "' value");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

 

 

 

如果要进行序列化的类实现了Serializable接口,则序列化和反序列化更加简单。

 

import java.io.Serializable;

public class TestBean implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 8983605225929184344L;

    private String strStr;

    private String strStrss;

    private String consoleStr;

    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getConsoleStr() {
        return consoleStr;
    }

    public void setConsoleStr(String consoleStr) {
        this.consoleStr = consoleStr;
    }

    public String getStrStrss() {
        return strStrss;
    }

    public void setStrStrss(String strStrss) {
        this.strStrss = strStrss;
    }

    public String getStrStr() {
        return strStr;
    }

    public void setStrStr(String strStr) {
        this.strStr = strStr;
    }
}

 

 

import java.io.Console;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class animal {
    void eat() {
        System.out.print(" animal eat ");
    }
}

class horse extends animal {
    void eat(int a) {
        System.out.print(" horse eat ");
    }
}

public class test {
    public static void main(String args[]) {
        // animal a = new horse();
        // a.eat();
        //
        // animal b = new animal();
        // b.eat();
        TestBean tb = new TestBean();
        try {
            FileOutputStream fo = new FileOutputStream("bean.ser");
            ObjectOutputStream dataO = new ObjectOutputStream(fo);
            tb.setStrStr("(*^__^*) 嘻嘻……");
            tb.setStrStrss("O(∩_∩)O哈哈~");

            // 控制台
            Console co = System.console();
            String coStr = co.readLine();

            tb.setConsoleStr(coStr);           

            char password[] = co.readPassword();
       
            String pStr = "";
            for (char t: password) {
                pStr += t;
            }
            tb.setPassword(pStr);
            System.out.println(pStr);
            // 序列化
            dataO.writeObject(tb);

            FileInputStream fi = new FileInputStream("bean.ser");
            ObjectInputStream dataI = new ObjectInputStream(fi);
            // 反序列化
            TestBean tbI = (TestBean) dataI.readObject();

            System.out.println(tbI.getStrStr());
            System.out.println(tbI.getStrStrss());

            System.out.println("控制台输入的值");
            System.out.println(tbI.getConsoleStr());

            System.out.println("控制台输入的密码");
            System.out.println(tbI.getPassword());

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

 

 

序列化formbean到字符串

public String goIndex(ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // formbean
        IntAir0006Form formBean = (IntAir0006Form) form;
        ByteArrayOutputStream bos = null;
        ZipOutputStream zos = null;
        ObjectOutputStream oos = null;
        try {
            // 字节数组输出流
            bos = new ByteArrayOutputStream();
            // 压缩方法
            zos = new ZipOutputStream(bos);
            zos.setMethod(ZipEntry.DEFLATED);
            zos.putNextEntry(new ZipEntry("a"));
            // 序列化
            oos = new ObjectOutputStream(zos);
            oos.writeObject(formBean);
            zos.closeEntry();

            // 转换编码
            String formBeanStr = new String(bos.toByteArray(), "ISO-8859-1");

            // 转换为 UTF-8
            String encodedCookieValue = java.net.URLEncoder.encode(formBeanStr,
                    "UTF-8");
            // 保存序列化的字符串
            formBean.setSerStr(encodedCookieValue);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (zos != null) {
                    zos.close();
                }
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
        }

        return "";
    }

 

    /**
     *
     * 反序列化取得Form
     *
     * @param rBean
     * @return
     * @throws Exception
     */
    public static IntAir0006Form getFormFromStr(IntAir0006Form rBean)
            throws Exception {
        IntAir0006Form formBean = null;
        InputStream in = null;
        ZipInputStream zin = null;
        ObjectInputStream oin = null;

        try {
            // 按照UTF-8编码
            String decoderCookieValue = java.net.URLDecoder.decode(rBean
                    .getSerStr(), "UTF-8");
            // 取得字节数组
            byte[] data = decoderCookieValue.getBytes("ISO-8859-1");
            // 字节数组输入流
            in = new ByteArrayInputStream(data);
            // zip输入流 解压缩
            zin = new ZipInputStream(in);
            zin.getNextEntry();
            // 反序列化 取得formBean
            oin = new ObjectInputStream(zin);
            formBean = (IntAir0006Form) oin.readObject();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (zin != null) {
                    zin.close();
                }
                if (oin != null) {
                    oin.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
        }
        return formBean;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值