1. 程式人生 > >讀取檔案內容並替換內容後生成新檔案

讀取檔案內容並替換內容後生成新檔案

 /**
      * 讀取檔案並替換其中的路徑,然後儲存檔案
      * @param filePath 讀取檔案路徑
      * @param savePath 儲存檔案路徑
      */
     private void changeContent(String filePath, String savePath) {
		// filePath 要讀取的檔案 savePath 要寫入的檔案
		BufferedReader br = null;
		BufferedWriter bw = null;
		String content = "";
		try {
			// 以下讀取和寫入都轉成UTF-8 防止亂碼
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					filePath), "UTF-8"));
			bw = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(savePath), "UTF-8"));
			StringBuffer str = new StringBuffer("替換後的內容");
			String line;
			while((line = br.readLine()) != null && (line != "")) {
				content = line + br.readLine();
				bw.write(content.replaceAll("要替換的內容", str.toString()).replace(
						"null", ""));
			}
			bw.flush();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				if(br != null)
					br.close();
				if(bw != null)
					bw.close();
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
	}