文件的读写操作 代码详解

public class FileOperation {

//读文件
public static UserInfo[] readFile(){
//把文件中的数据先读到Properties容器中
Properties props =new Properties();
try {
props.load(new FileInputStream("UserInfo.properties")); //取文件
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//把Properties中的字符串数据转换为UserInfo对象,放到UserInfo[]中
UserInfo [] allUserInfos=new UserInfo[props.size()];
Set allkey =props.keySet();
for(Object key:allkey){
String value = props.getProperty((String) key);
String[] userInfo=value.split("[&]"); //出现&就拆分前后字符
UserInfo user=new UserInfo(userInfo[0],userInfo[1],Float.parseFloat(userInfo[2]));
allUserInfos[Integer.parseInt((String) key)]=user;

}
return allUserInfos;
}


//写文件
public static void writeFile(UserInfo[] allUsers){
//把UserInfo[]中的数据,放入到Properties中
Properties props = new Properties(); //获得一个props容器类
for(int i=0;i<allUsers.length;i++){
String key =Integer.toString(i); //将i转换为String类型装到键中
String value = allUsers[i].getUsername()+"&"+allUsers[i].getPassword()+"&"+
allUsers[i].getAccount(); //将第i位的用户名密码余额装到字符串value(值)中

props.setProperty(key, value); //传键和值给props
}
//把Properties中的数据写入文件中
try {
props.store(new FileOutputStream("UserInfo.properties"), null); //存文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

public static void main(String []args){
UserInfo [] allUsers = new UserInfo[5];
for(int i=0;i<allUsers.length;i++){
allUsers[i]=new UserInfo("zhang"+(i+1),"123456"+(i+1),(i+1)*1000);
}
writeFile(allUsers);
readFile();
}
}

posted @ 2016-06-05 22:55  Blueses  阅读(316)  评论(0编辑  收藏  举报