java保存数据
java存储数据 windows下,有几种方式
1、使用缓存 Preferences
2、文件存储 一般有一下两种方式
-使用 .properties文件
-使用 .xml文件
使用Preferences 程序记录1中已经使用
Preferences prefs = Preferences.userNodeForPackage(Main.class); //取得实体
String username = prefs.get("username", ""); //获取数据
prefs.putLong("id", staff.getLongValue("id")); //设置数据
prefs.put("username", staff.getString("username"));
使用 .properties文件
// 需先判断文件是否存在,否则会报错
File fileDir=new File("D:\\operation");
if(!fileDir.exists()){
fileDir.mkdirs();
}
File file=new File(fileDir,"operation.properties");
if(!file.exists()){
file.createNewFile();
}
//写入
Properties prop1 = new Properties();
FileOutputStream prop= new FileOutputStream(file, false); //flase 表示是否append 追加
prop.setProperty("username", agent.getString("username"));
prop.store(oFile, null);
oFile.close();
//读取
Properties prop = new Properties();
try {
File file = new File(file);
boolean exists = file.exists();
if (exists) {
InputStream in = new BufferedInputStream(new FileInputStream(file ));
prop.load(in);
Iterator<String> it = prop.stringPropertyNames().iterator();
while (it.hasNext()) {
String key = it.next();
userName.setText(key);
password.setText(prop.getProperty(key));
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}