java實現mysql數據庫的備份及還原

備份:java

public static void backup() {
		try {
			Runtime rt = Runtime.getRuntime();

			// 調用 調用mysql的安裝目錄的命令
			Process child = rt
					.exec("e:\\MySQL\\bin\\mysqldump -h localhost -uroot -p123 db_name");
			// 設置導出編碼爲utf-8。這裏必須是utf-8
			// 把進程執行中的控制檯輸出信息寫入.sql文件,即生成了備份文件。注:若是不對控制檯信息進行讀出,則會致使進程堵塞沒法運行
			InputStream in = child.getInputStream();// 控制檯的輸出信息做爲輸入流

			InputStreamReader xx = new InputStreamReader(in, "utf-8");
			// 設置輸出流編碼爲utf-8。這裏必須是utf-8,不然從流中讀入的是亂碼

			String inStr;
			StringBuffer sb = new StringBuffer("");
			String outStr;
			// 組合控制檯輸出信息字符串
			BufferedReader br = new BufferedReader(xx);
			while ((inStr = br.readLine()) != null) {
				sb.append(inStr + "\r\n");
			}
			outStr = sb.toString();

			// 要用來作導入用的sql目標文件:
			FileOutputStream fout = new FileOutputStream("c:\\test.sql");
			OutputStreamWriter writer = new OutputStreamWriter(fout, "utf-8");
			writer.write(outStr);
			writer.flush();
			in.close();
			xx.close();
			br.close();
			writer.close();
			fout.close();

			System.out.println("");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

 

還原:mysql

public static void restore(String databaseName) {
		try {
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime
					.exec("e:\\MySQL\\bin\\mysql.exe -hlocalhost -uroot -p123 --default-character-set=utf8 "
							+ databaseName);
			OutputStream outputStream = process.getOutputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream("C:\\test.sql"), "utf-8"));
			String str = null;
			StringBuffer sb = new StringBuffer();
			while ((str = br.readLine()) != null) {
				sb.append(str + "\r\n");
			}
			str = sb.toString();
			// System.out.println(str);
			OutputStreamWriter writer = new OutputStreamWriter(outputStream,
					"utf-8");
			writer.write(str);
			writer.flush();
			outputStream.close();
			br.close();
			writer.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
相關文章
相關標籤/搜索