文件的读写操作 代码详解

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();
}
}

转载于:https://www.cnblogs.com/Blueses/p/5562178.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值