因爲須要對文本文件的部份內容進行更新操做,具體操做是須要先將文本文件內容讀取出來,暫以字符串形式保存,而後進行匹配替換,並將字符串從新寫入原文本文件中。sql
規劃使用BufferedReader進行讀取,使用PrintWriter進行寫入操做app
BufferedReader br = null; PrintWriter pw = null; StringBuilder sqlMapConf = new StringBuilder(); try { File sqlMapConfFile = new File(sqlMapConfPath, name); br = new BufferedReader(new InputStreamReader( new FileInputStream(sqlMapConfFile), "UTF-8")); pw = new PrintWriter(sqlMapConfFile,"UTF-8"); String str = ""; while ((str = br.readLine())!=null) { sqlMapConf.append(str+"\r\n"); } str = sqlMapConf.toString().replaceFirst("\\*sqlMap映射文件\\*", config); pw.write(str); System.out.println(str); } catch (FileNotFoundException e) { throw new RuntimeException(name+"文件未找到!"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(name+"文件IO處理異常!"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(name+"文件處理出現未知異常!"); }finally { if (pw!=null) { pw.close(); } if (br!=null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }
測試時發現,原文本文件內容會被清空,且未有內容寫入,也無異常報錯信息測試
經過分析推測,輸入流未關閉的狀況下,輸出流操做同一路徑文件,會形成衝突,輸入流會認爲該文件不存在並從新建立同名文件覆蓋原文件,然後輸入流實際讀取的是一個空文件,那麼輸出流寫入的內容也爲空,最後形成文件內容置空的現象。ui
在輸入流操做完該文件後,輸出流再進行文件操做,代碼糾正以下:code
BufferedReader br = null; PrintWriter pw = null; StringBuilder sqlMapConf = new StringBuilder(); try { File sqlMapConfFile = new File(sqlMapConfPath, name); br = new BufferedReader(new InputStreamReader( new FileInputStream(sqlMapConfFile), "UTF-8")); // pw = new PrintWriter(sqlMapConfFile,"UTF-8"); String str = ""; while ((str = br.readLine())!=null) { sqlMapConf.append(str+"\r\n"); } str = sqlMapConf.toString().replaceFirst("\\*sqlMap映射文件\\*", config); pw = new PrintWriter(sqlMapConfFile,"UTF-8");//糾正增長的代碼 pw.write(str); System.out.println(str); } catch (FileNotFoundException e) { throw new RuntimeException(name+"文件未找到!"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(name+"文件IO處理異常!"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(name+"文件處理出現未知異常!"); }finally { if (pw!=null) { pw.close(); } if (br!=null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }