天天看點

java中将對象寫入檔案

/**
 * Object2FileUtils裡面的工具類 
 * 
 * @author
 *
 */
public class Bean4Caches implements Serializable {

	public HashMap<String, String> map=new HashMap<String, String>();
	
	public CookieStore cookieStore;
	
	
}
           
public class ObjectToFileUtils {
	
	
	private static final String Path_Cache="cacheLocalValue.txt";
	
	public static void writeObject(Bean4Caches cacheBean) {
		FileOutputStream outStream=null;
		try {
			
			if(null==cacheBean){
				return;
			}
		   outStream = new FileOutputStream(Path_Cache);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
			
			objectOutputStream.writeObject(cacheBean);
			outStream.close();
			
			System.out.println(" cache  ----- successful");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null!=outStream){
					outStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static  Bean4Caches readObject(){
		FileInputStream freader = null;
		try {
			
			File file=new File(Path_Cache);
			if(!file.exists()){
				System.out.println("--------------------->  沒有緩存檔案");
				return null;
			}
			
			freader = new FileInputStream(Path_Cache);
			ObjectInputStream objectInputStream = new ObjectInputStream(freader);
			Bean4Caches bean = (Bean4Caches) objectInputStream.readObject();
			 
			 return bean;
			 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(null!=freader){
					freader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
		
	}
	
}