---
title: "利用Window temp存储数据"
author: "gdntx"
date: "2009-08-06T13:25:53Z"
tags: []
slug: "window-temp"
draft: false
lastmod: "2009-08-06T13:27:02Z"
id: 441552
url: "https://gdntx.iteye.com/blog/441552"
---

我们可以把数据存放在C:\\Documents and Settings\\Administrator\\Local Settings\\Temp里，要用的时候可以从temp取。

程序代码如下:

```
package com.javaeye.testjbpm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class Persistence {
	
	private static Map variables = null;
```

```
	
	//java.io.tmpdir,不能改，这是JVM定义的
	private static String tmpfile = System.getProperty("java.io.tmpdir") + "/temp.object";//temp.object就是存放的文件名
	static{
		//加载文件
		try{
			
			if(new File(tmpfile).exists()){
				FileInputStream in = new FileInputStream(tmpfile);
				ObjectInputStream s = new ObjectInputStream(in); 
			    variables = (Map)s.readObject();
			}
			
			if(variables == null){
				variables = new HashMap();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//设置一个变量的值
	public static void setVariable(String name,Serializable object){
		if(variables != null){
			variables.put(name, object);
		}
		try {
			FileOutputStream fos = new FileOutputStream(tmpfile);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(variables);
			oos.flush();
			oos.close();
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//获取一个变量的值
	public static Serializable getVariable(String name){
		if(variables != null){
			return (Serializable)variables.get(name);
		}
		return null;
	}
	
}
```