Java 用FileReader 和 FileWriter 進行檔案讀寫(txt) (

n8765發表於2015-05-22




方法演示了從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();
}
}
}
}

相關文章