I/O流——替換文字檔案內容
阿新 • • 發佈:2019-02-20
public static void main(String[] args) throws IOException { //替換前字串 String before="a"; //替換後字串 String after="b"; //建立檔案讀流 FileReader reader=null; //建立檔案寫流 FileWriter writer =null; //使用StringBuilder對想儲存檔案內容 StringBuilder sb=new StringBuilder(); //宣告檔案讀入標識 int flag=0; //使用字元陣列讀入檔案 char[] temp=new char[1024]; File textFile=new File("f:\\1.txt"); try { //使用選擇的檔案建立讀流 reader=new FileReader(textFile); while((flag=reader.read(temp))!=-1){ //讀入檔案中的內容 sb.append(temp); } //替換字串 String content=sb.toString().replace(before, after); //建立檔案寫流 writer =new FileWriter(textFile); //將替換後的字串寫入到檔案 writer.write(content); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ writer.flush(); writer.close(); } }