Java 用FileReader 和 FileWriter 进行文件读写(txt) (

时间:2021-12-20 23:37:24




方法演示了从C:/xml/ro_person_0412.txt文件中读取个人的ID,电话,手机,地址信息导入Ldap
然后将导入结果写入带有根据当前时间生成的文件名的文件中"/C:/xml/updateresult"+sft.format(dt)+".txt"

—————ro_person_0412.txt————— 
ID1,12345678,1234567890,address1ID2,12345678,1234567890, ID3,123456,, ID4,,,

———————————————————   

private void updateUserByTxt() {
File inputfile = new File("/C:/xml/ro_person_0412.txt");
try {
List personList = new ArrayList();
FileReader fr = new FileReader(inputfile);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
//  System.out.println(s);
String[] data = s.split(",");
UserInfo userInfo = new UserInfo();
userInfo.setUid(data[0].trim());
userInfo.setTelephoneNumber(data[1].trim());
userInfo.setHomePhone(data[2].trim());
userInfo.setHomePostalAddress(data[3].trim());
personList.add(userInfo);
}
fr.close();
initLDAP(); // 初始化
System.out.println("总人数:"+personList.size());
int count1 = 0;
int count2 = 0;
SimpleDateFormat sft = new SimpleDateFormat("yyyyMMddHHmmss");
Date dt = new Date();
File f = new File("/C:/xml/updateresult"+sft.format(dt)+".txt");
f.createNewFile();
   FileWriter fw=null; 
   BufferedWriter bw=null; 
    
for (int i = 0; i < personList.size(); i++) {
System.out.println(i + 1);
UserInfo userInfo = (UserInfo) personList.get(i);
String uid = userInfo.getUid(); // 人员标识
String telephoneNumber = userInfo.getTelephoneNumber();// 办公电话
String homePhone = userInfo.getHomePhone();// 家庭电话
String homePostalAddress = userInfo.getHomePostalAddress(); // 家庭地址
fw = new FileWriter(f, true);
bw = new BufferedWriter(fw);
String msg ="";
// 人员对应的完整DN
String DN = "uid=" + uid + ",cn=employees," + baseDC;
ModificationItem mItem[] = new ModificationItem[3];
mItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("telephoneNumber", telephoneNumber)); // 办公电话
mItem[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("homePhone", homePhone)); // 家庭电话
mItem[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("homePostalAddress", homePostalAddress)); // 家庭地址
try {
ctx.modifyAttributes(DN, mItem);
count1 ++;
} catch (NamingException e) {
msg += "更新失败:uid=" + uid + "," + e.getMessage(); 
System.out.println(msg);
bw.write(msg);
bw.newLine();
bw.flush();
bw.close();
count2 ++;
}
}
fw = new FileWriter(f, true);
bw = new BufferedWriter(fw);
String msg = "总人数:"+personList.size()+"------更新人数:"+count1+"------更新失败人数:"+count2;
System.out.println(msg);
bw.write(msg);
bw.newLine();
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (null != ctx) {
try {
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
}