import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;



public class Test {
	public static void main(String[] args) throws IOException{
		backup("d:\\d.sql");
		recover("d:\\d.sql");
	}
	public static void backup(String path) throws IOException{
		Runtime runtime = Runtime.getRuntime();
		//-u后面是用户名,-p是密码-p后面最好不要有空格,-family是数据库的名字
		Process process = runtime.exec("mysqldump -u root -p123456 family");
		InputStream inputStream = process.getInputStream();//得到输入流,写成.sql文件
		InputStreamReader reader = new InputStreamReader(inputStream);
		BufferedReader br = new BufferedReader(reader);
		String s = null;
		StringBuffer sb = new StringBuffer();
		while((s = br.readLine()) != null){
			sb.append(s+"\r\n");
		}
		s = sb.toString();
		System.out.println(s);
		File file = new File(path);
		file.getParentFile().mkdirs();
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		fileOutputStream.write(s.getBytes());
		fileOutputStream.close();
		br.close();
		reader.close();
		inputStream.close();
	}
	public static void recover(String path) throws IOException{
		Runtime runtime = Runtime.getRuntime();
		//-u后面是用户名,-p是密码-p后面最好不要有空格,-family是数据库的名字,--default-character-set=utf8,这句话一定的加
		//我就是因为这句话没加导致程序运行成功,但是数据库里面的内容还是以前的内容,最好写上完成的sql放到cmd中一运行才知道报错了
		//错误信息:
		//mysql: Character set 'utf-8' is not a compiled character set and is not specified in the '
		//C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\Index.xml' file ERROR 2019 (HY000): Can't
		// initialize character set utf-8 (path: C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\),
		//又是讨人厌的编码问题,在恢复的时候设置一下默认的编码就可以了。
		Process process = runtime.exec("mysql -u root -p123456 --default-character-set=utf8 family");
		OutputStream outputStream = process.getOutputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
		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();
	}
}
最近下载更多
sfy_1802661689  LV2 2023年7月3日
crosa_Don  LV18 2022年7月19日
ZDM-希童  LV1 2022年5月18日
jachyn  LV6 2020年9月9日
阿凝是个小可爱  LV14 2020年5月22日
小舟呀  LV12 2020年3月25日
ncd12320  LV8 2020年1月12日
lyd19931203  LV21 2019年12月11日
luohaipeng  LV23 2019年12月5日
小熊熊的  LV2 2019年11月18日
最近浏览更多
sfy_1802661689  LV2 2023年7月3日
Dominick  LV14 2022年11月17日
crosa_Don  LV18 2022年7月19日
ZDM-希童  LV1 2022年5月18日
a1412780985  LV1 2022年4月20日
里更debug  LV10 2022年4月8日
liuziqi0529  LV4 2022年3月5日
tcdt160426  LV1 2021年9月23日
laimao  LV1 2021年5月20日
alang94  LV5 2021年5月12日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友