Copy Code code as follows:
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 After the user name,-p is the password-p best not to have spaces,-family is the name of the database
Process Process = Runtime.exec ("Mysqldump-u root-p123456 Family");
InputStream InputStream = Process.getinputstream ()//Get input stream, write. sql file
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 After the user name,-p is the password-p best not to have spaces,-family is the name of the database,--default-character-set=utf8, this sentence must add
//I just because this sentence did not add to the success of the program, but the contents of the database or the previous content, it is best to write on the completion of the SQL into a CMD operation to know the error
//Error message:
//mysql:character set ' Utf-8 ' is not a compiled Character set and isn't specified in '
//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\\),
It is also an annoying coding problem, set the default encoding when you restore it.
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 ();
}
}