i have a textfile that contains 1300000 lines.i have written the java code for importing it into a mysql database.In the java class i have a method called textloadutility() which is called from a jsp page.Can someone give the asyncronous thread implementation of this java program.
package Snomed;
import catalog.Root;
import java.io.*;
import java.sql.PreparedStatement;
import org.json.JSONObject;
public class Textfileimport {
public String textloadutility() throws Exception {
Root oRoot = null;
PreparedStatement oPrStmt = null;
FileReader in = null;
BufferedReader br=null;
final int batchSize = 1000;
int count = 0;
JSONObject oJson = null;
String str=null;
oJson = new JSONObject();
oJson.put("status","failure");
str=oJson.toString();
try {
oRoot = Root.createDbConnection(null);
String sql = "INSERT INTO textfiledata (col1,col2,col3,col4,col5,col6,col7,col8,col9) VALUES( ?, ?, ?,?,?,?,?,?,?)";
oPrStmt = oRoot.con.prepareStatement(sql);
in = new FileReader("C:/Users/i2cdev001/Desktop/snomedinfo_data.txt");
br = new BufferedReader(in);
String strLine;
while ((strLine = br.readLine()) != null){
String [] splitSt =strLine.split("\\t");
String dat1="",dat2="",dat3="",dat4="",dat5="",dat6="",dat7="",dat8="",dat9="";
dat1=splitSt[0];
dat2=splitSt[1];
dat3=splitSt[2];
dat4=splitSt[3];
dat5=splitSt[4];
dat6=splitSt[5];
dat7=splitSt[6];
dat8=splitSt[7];
dat9=splitSt[8];
oPrStmt.setString(1, dat1);
oPrStmt.setString(2, dat2);
oPrStmt.setString(3, dat3);
oPrStmt.setString(4, dat4);
oPrStmt.setString(5, dat5);
oPrStmt.setString(6, dat6);
oPrStmt.setString(7, dat7);
oPrStmt.setString(8, dat8);
oPrStmt.setString(9, dat9);
oPrStmt.addBatch();
if (++count % batchSize == 0) {
oPrStmt.executeBatch();
oPrStmt.clearBatch();
}
}
oPrStmt.executeBatch();
oJson.put("status","sucess");
str=oJson.toString();
in.close();
br.close();
System.out.println("sucessfully imported");
}
catch (Exception e) {
oJson.put("status","failure");
str=oJson.toString();
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
} finally {
oPrStmt = Root.EcwClosePreparedStatement(oPrStmt);
oRoot = Root.closeDbConnection(null, oRoot);
}
return str;
}
}
Here is the solution for your problem,
File IO should not be async so first Thread-1 should read the file batch by batch and put that into some shared queue.
The another multi-threaded thread should read the contents of the queue and push it into db. You could implement this using ExecutorService class of java concurrent package. And co-ordinate all those threads using CountDown latch.
Once all the lines are read from the file by the single thread then it will return to the caller.
After all those queue entries are processed the db processing threads will be closed and respective countdown latch also will be decreased and finish once it move to 0.
You should use the future response to the actual caller so that after finishing of all those threads you will get the response.
This is high level view.
Related
This question already has answers here:
How to split the large size .txt file data into small portion and insert into database?
(2 answers)
Read data from txt file and insert it into database using java
(2 answers)
Closed 4 years ago.
I have a text file consisting of several lines.
I want to add the whole lines to the table of database.
Before it is inserted to table, it should be substring to get fields value of database table. I think my code (Query) is not good for big data. I know there is other way to do that condition.
public class ReaderFilesData {
LinkedList<String> listFiles = new LinkedList<String>();
private Path path = Paths.get("src/FilesDownloaded/");
DataTRX dataTRX = new DataTRX();
public void readFiles() {
File[] listFile = new File(path.toString()).listFiles();
for (File file : listFile) {
if (file.isFile()) {
listFiles.add(file.getName());
}
}
System.out.println("Total Files : " +listFiles.size());
}
public void readData() {
Path pathsourceFile;
String line;
BufferedReader reader;
for (int i=0; i<listFiles.size(); i++) {
try {
String fileName = listFiles.get(i);
System.out.println("FileName : " +fileName);
pathsourceFile = Paths.get("src/FilesDownloaded/"+fileName+"");
reader = new BufferedReader(new FileReader(pathsourceFile.toString());
while ((line = reader.readLine())!=null) {
int startPoint = line.lastIndexOf(';')+1;
String valueLine = new String(line.substring(startPoint));
System.out.println("Transaction data : " +valueLine);
dataTRX.setId(valueLine.substring(0,2));
dataTRX.setAmount(Integer.parseInt(valueLine.substring(2, 10)));
dataTRX.setDesc(valueLine.substring(10, 18));
System.out.println("getId : " + dataTRX.getId());
System.out.println("getAmount : " + dataTRX.getAmount());
System.out.println("getDesc : " + dataTRX.getDesc());
importData(dataTRX.getId(),
dataTRX.getAmount(),
dataTRX.getDesc(),
}
reader.close();
} catch (Exception e) {
e.getMessage();
}
}
}
public void importData(String id, int amount, String discount ) {
String insertData = "INSERT INTO tbl_trx (id, amount, desc) "
+ "VALUES (?,?,?)";
try {
try (PreparedStatement ps = GeneralRules.conn.prepareStatement(insertData)) {
ps.setString(1, id);
ps.setInt(2, amount);
ps.setString(4, desc);
ps.executeUpdate();
System.out.println("Data successfully update to database!!!\n");
ps.close();
}
} catch (Exception e) {
e.getMessage();
}
}
This is example data of file.txt
320000000200000001
2G0000000500000002
AB0000001500000001
I do substring data base on line above :
substring id,amount,discount (32,00000002,00000001)
substring id,amount,discount (2G,00000005,00000002)
substring id,amount,discount (AB,00000015,00000001)
Your code seems good to me. But If I would have written it, below optimization/replacement, I would have done
1) Use List instead of LinkedList in variable declaration and remove generic String from reference point. Something like
List<String> listFiles = new LinkedList<>();
Link for more explanation on this
2) Similar to using try with resource you did for PreparedStatement, I would do the same for BufferedReader. This would remove the need to close the `BufferedReader' in the end
try (BufferedReader reader = new BufferedReader(new FileReader(pathsourceFile.toString())))
Link for more explanation on this
3) Because you have used try with resource for PreparedStatement, there is no need to have ps.close(), because preparedstatement implements AutoCloseable. So try with resouce will take care of it
4) Instead of e.getMessage(), I would have used e.printStackTrace() because it would give me more information about the error
As far as your use of sub-string is concerned, I would have used it, or would have use regex to split the string.
If number of rows to be inserted are more, which I think is your case, instead of calling executeUpdate() everytime, go with Batch mode. i.e add statements to PreparedStatement batch using addBatch() and execute in one go with executeBatch()
I'm working on a programming online judge project like HackerRank,Codeforces etc...
I have thread pool and when requests comes, the web services gets a thread from thread pool and that thread compiles the code with ProcessBuilder(everything is okey until here), after the compilation, that thread starts execution part by using again a new Processbuilder. But my "time limit exceed" part is not calculated properly. When number of requests is increased, then I think that the process works slowly and for this reason any basic code gets time out. How can I measure the execution time of the code which is executed by a process ?(the measurement should not been affected by number of requests)
EDIT: my process should waitfor user time of the process.But I dont know how to do this.
My execution code is here:
package org.anil.CodeChecker.process;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.concurrent.TimeUnit;
import org.anil.CodeChecker.model.ExecutorModel;
public class Executor {
private ProcessBuilder p;
private String path;
private String input;
private String output;
private String lang;
private long timeInMillis;
public Executor(String path,String input, String output,String lang,long timeInMillis ){
this.path = path;
this.input = input;
this.output = output;
this.lang = lang;
this.timeInMillis = timeInMillis;
}
public ExecutorModel execute(){
ExecutorModel model = new ExecutorModel();
System.out.println("Code started executing");
if(lang.equals("java")){
p = new ProcessBuilder("java","Solution");
}
else if(lang.equals("c")){
p = new ProcessBuilder("./a.out");
}
else if(lang.equals("c++")){
p = new ProcessBuilder("./a.out");
}
else{
System.out.println("language is not correct...");
p = null;
}
p.directory(new File(path));
p.redirectErrorStream(true);
// System.out.println("Current directory "+System.getProperty("user.dir"));
try{
Process pp = p.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(pp.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
/*process e input veriliyor bu kısımda */
OutputStream outputstream = pp.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputstream));
writer.write(input);
writer.flush();
writer.close();
if(!pp.waitFor(timeInMillis, TimeUnit.MILLISECONDS)){
System.out.println("TİME LİMİT EXCEED !!!! ");
model.setTimelimit(true);
return model;
}
else{
model.setTimelimit(false);
int exitCode = pp.exitValue();
System.out.println("Exit Value = "+pp.exitValue());
if(exitCode != 0){
System.out.println("RUNTIME ERROR !!!!!!");
model.setSuccess(false);
model.setRuntimeerror(true);
return model;
}
}
while ( (line = reader.readLine()) != null) {
builder.append(line);
//builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(" output:"+result+" input:"+input);
if(result.charAt(result.length()-1) == ' ')
result = result.substring(0, result.length()-1);
if(result.equals(output)){
model.setSuccess(true);
model.setWronganswer(false);
System.out.println("OUTPUT (SUCCESS) = "+result);
return model;
}
else{
model.setSuccess(false);
model.setWronganswer(true);
System.out.println("OUTPUTTT (FAIL) = "+result);
return model;
}
}catch(IOException ioe){
System.err.println("in execute() "+ioe);
}catch (InterruptedException ex){
System.err.println(ex);
}
System.out.println("CODE EXECUTION FINISHED !");
return model;
}
}
Have you tryed to:
public long getCpuTime() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime() : 0L;
}
Using that method as the thread starting a process starts, and then use it again when that thread ends (since it then also ends the process as I understand it), then check delta (aka difference, last usage of the method minus first usage), to get the time how long that thread has been running, thus indirectly getting the time that the process took?
If Im not misstaken, that approach would be better then using for instance System.currentTimeMillis() since it counts the cpu time given to that specific thread, excluding time used by other threads as well as other system processes running in the background.
I recently asked a question that helped me understand what a C program is doing in terms of Java. My goal is now to perform a C-like fork of two new child processes, while keeping track of parent process IDs and child process Ids. I am unsure, however, if this is possible.
Here, I've attempted to initiate process P and run two child processes (which I believed to be the InputStreamReaders isr and wasr ). I've gotten the PID of process P. But, where I'm stuck is the fact that InputStreamReader is not really a process, so I can't get the process ID.
I'll mention like I did in the other post that this is a homework assignment which provides C code instruction but urging Java code responses. The end goal is to be able to print "Child process ID of Parent process ID has begun" and "Child process ID has terminated" -- this is why it's important that I keep track of everyone's ID.
I found this other post, but I'm not sure how to adapt it.
UPDATE : With help of another SO user, I've realized that i may be approaching the problem in the wrong way. Here, parent process is the java process and child process is the native process. Updated code below.
Original Code
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
class processesorigin {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("/bin/ls");
final InputStream is = p.getInputStream();
final InputStream was = p.getInputStream();
Thread t = new Thread(new Runnable() {
public void run() {
InputStreamReader isr = new InputStreamReader(is);
InputStreamReader wasr = new InputStreamReader(was);
int ch;
try {
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
while ((ch = wasr.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
p.waitFor();
t.join();
int pid = 0;
if(p.getClass().getName().equals("java.lang.UNIXProcess")) {
try {
Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
pid = f.getInt(p);
}
catch (Throwable e) {
}
}
System.out.println("Process " + pid + " terminates.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
UPDATED CODE Using these tips and another SO user, I have found how to capture the Java process ID. There is however, still an issue with signaling of the start of each process. This might be another question though.
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import sun.management.VMManagement;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
class processesorigin {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("/bin/ls");
Process q = Runtime.getRuntime().exec("/bin/ls");
final InputStream is = p.getInputStream();
final InputStream was = q.getInputStream();
/*get PID of Java process*/
final String runtimeName = ManagementFactory.getRuntimeMXBean().getName();
final String jvmPid = runtimeName.split("#")[0];
int pid = 0;
int qid = 0;
if(p.getClass().getName().equals("java.lang.UNIXProcess")) {
/* get the PID of child processes : native ls command*/
try {
Field f = p.getClass().getDeclaredField("pid");
Field g = q.getClass().getDeclaredField("pid");
f.setAccessible(true);
g.setAccessible(true);
pid = f.getInt(p);
qid = g.getInt(q);
}
catch (Throwable e) {
}
}
final int pidCopy = pid;
final int qidCopy = qid;
Thread t = new Thread(new Runnable() {
public void run() {
InputStreamReader isr = new InputStreamReader(is);
InputStreamReader wasr = new InputStreamReader(was);
int ch;
try {
System.out.print("Child process " + pidCopy + " of Parent process " + jvmPid + " begun.");
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
System.out.print("Child process " + qidCopy + " of Parent process " + jvmPid + " begun.");
while ((ch = wasr.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
p.waitFor();
q.waitFor();
t.join();
System.out.println("Child process " + pidCopy + " terminated.");
System.out.println("Child process " + qidCopy + " terminated.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Regarding your update: The way how you are getting the PID of the native child process should also work on OSX.
Since your assignment is to start two child processes from Java (right?) you can just start two native processes using Runtime.getRuntime().exec(), read and print stdout of each of them, and get and print the PID of each of them.
You can choose to run both processes in the main thread or start each process in a separate thread, basically like it is done in your example.
I am not sure if I fully understand what you want to achieve but maybe this helps you anyway. It is a tiny C program, a kind of wrapper that you can use to start a native process and obtain its PID from Java code:
#include <unistd.h>
#include <stdio.h>
/*
* Purpose of this "program" is to write its PID to stdout so that
* it can be read by a Java program which then can shutdown this
* process gently by sending for example SIGINT to it.
* After printig its PID the process executes the program given
* as argument.
*/
int main(int argc, char *argv[]) {
if(argc < 3) {
fprintf(stderr,"Usage: %s <program> <name> [arg] ...\n", argv[0]);
return -1;
}
/* Write the PID of the process to stdout */
fprintf(stdout,"%i\n", getpid());
/* Flush the buffers */
fflush(NULL);
/*
* Execute the program (specified as file or full path) given as first
* argument in the current process.
*/
return execvp(argv[1], argv + 2);
}
Assuming above code was compiled and the executable copied to /usr/local/bin/jpwrapper, it can be used from Java to run a native process like ls -l /dev, print out the PID when the process started, print its stdout and again the PID when it terminated:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PID {
public static void main(final String[] args) throws Exception {
final Process process = Runtime.getRuntime().exec(new String[] {
"/usr/local/bin/jpwrapper",
"/bin/ls", "ls", "-l", "/dev"});
String pid = null;
try (final BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
// First line of output from the wrapper is the PID
String line = reader.readLine();
pid = line;
System.out.println(String.format(
"Process with PID %s started", pid));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
final int exitCode = process.waitFor();
System.out.println(String.format(
"Process with PID %s terminated with exit code %s",
pid, exitCode));
}
}
But, like I already admitted in my comment, getting the PID from UnixProcess is easier (but also hacky).
Excuse any wrong practices as I am very new to threading. I have a program that calls my api and gets data back in json format. Each request returns a row of data in json format. All together I need to retrieve about 2,000,000 rows a day which means 2,000,000 requests (I understand that this is bad design, but the system was not designed for this purpose it is just what I need to do for the next couple of weeks). When I tried running it on a single thread I was processing about 200 requests a minute which is much too slow. As a result I created 12 threads and I was processing 5500 rows a minutes which was a great improvement. The problem was only about on average 90% of the rows were inserted into the database as I ran it a few times to make sure. Before each insert printed to a file each URL which was sent and then I checked to see if each insert statement was successful (returned 1 when executed ) and it all seems fine. Every time I run it it inserts about 90% but it does varies and it has never been a consistent number. Am I doing something wrong inside my java code? Essentially the code starts in main by creating 12 threads. Each thread's creates a run method which calls a new instance of MySQLPopulateHistData and passes a start and end integer which are used in the insert statement for ranges. I have done many system.out.println type testing and can see all the threads do start and all the 12 instances (one instance for each thread) called are executing? Does anyone have any idea what it could be?
MAIN:
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainClass {
public static void main(String[] args) {
try {
//create a pool of threads
Thread[] threads = new Thread[12];
// submit jobs to be executing by the pool
for (int i = 0; i <12; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
try {
new MySQLPopulateHistData(RangeClass.IdStart, RangeClass.IdEnd);
} catch (Throwable e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
});
threads[i].start();
Thread.sleep(1000);
RangeClass.IdStart = RangeClass.IdEnd + 1;
RangeClass.IdEnd = RangeClass.IdEnd + 170000;
}
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyDataSourceFactory.class
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.sql.DataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class MyDataSourceFactory {
static String url = "jdbc:mysql://localhost:3306/my_schema";
static String userName = "root";
static String password = "password";
public synchronized static DataSource getMySQLDataSource() {
MysqlDataSource mysqlDS = null;
mysqlDS = new MysqlDataSource();
mysqlDS.setURL(url);
mysqlDS.setUser(userName);
mysqlDS.setPassword(password);
return mysqlDS;
}
}
MySQLPopulateHistData.class
public class MySQLPopulateHistData {
public MySQLPopulateHistData(int s, int e ) throws IOException, Throwable{
getHistory(s,e);
}
public synchronized void getHistory(int start, int end){
DataSource ds = MyDataSourceFactory.getMySQLDataSource();
Connection con = null;
Connection con2 = null;
Statement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try {
con = ds.getConnection();
con2 = ds.getConnection();
stmt = con.createStatement();
stmt2 = con.createStatement();
rs = stmt.executeQuery("SELECT s FROM sp_t where s_id BETWEEN "+ start +" AND "+ end + " ORDER BY s;");
String s = "";
while(rs.next()){
s = rs.getString("s");
if( s == ""){
}
else{
try{
URL fullUrl = new URL(//My Url to my api with password with start and end range);
InputStream is = fullUrl.openStream();
String jsonStr = getStringFromInputStream(is);
JSONObject j = new JSONObject(jsonStr);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("quote");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String symbol = obj.getString("s");
stmt2.executeUpdate("INSERT into sp2_t(s) VALUES ('"+ s +"') BETWEEN "+start+" AND "+ end +";");
}
}
catch(Exception e){
}
}
s = "";
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
if(stmt2 != null) stmt.close();
if(con2 != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
UPDATE:
So I put:
(if s.equals("")){
System.out.println("EMPTY");
}
and it never printed out EMPTY. After the JSON requests gets converted to the JSONArray I added:
if(arr.length()>0){
StaticClassHolder.cntResponses++;
}
This is just a static variable in another class that gets incremented everytime there is a valid JSON response. It equalled to the exact right amount it was supposed to be. So it seems as if the URL gets all the responses properly, parses them properly, but is not INSERTING them properly into the database? I can't figure out why?
I also faced the similar issue while inserting records in Oracle. Since I didn't find any concrete solution. I tried with single thread and all went fine.
There are several reasons why this does not work:
A normal computer can only handle about 4-8 threads in total per cpu. As the system uses some of thise threads you would only be able to run some threads at the same time. The computer handles this by pausing some threads then running another thread.
If you try to send several queries through the socket to the mysql server at the same time chanses are that some of the requests will not work and you lose some of your data.
As for now I do not have any solution for faster updates of the table.
I'm trying to restore a MySQL database from a file generated with mysqldump.
I do it with an ArrayList that contains each query of the restoration plan and I execute each one of them with a Statement.
But sometimes, it stops on some point of the proccess (it can be different on different executions). It doesn't show any error message; it just hangs (when this happens, I need to restart the Mysql service).
This is the code of the restoration:
ArrayList<String> sql;
int res;
FileSQLCommandManager fichero = null;
try {
if (pass == null)
conectar(conn);
else
conectar(conn, pass);
Statement st = null;
st = conn.createStatement();
st.executeUpdate("SET FOREIGN_KEY_CHECKS=0");
PreparedStatement stConstraints = null;
String cadenaSQL = null;
String cadenaSQLConstraints = null;
String cadenaConstraints;
ResultSet rs;
boolean ejecutar = false;
fichero = new FileSQLCommandManager(fic);
fichero.open();
sql = fichero.read();
cadenaSQL = "";
for (int i = 0; i < sql.size(); i++) {
cadenaSQL = sql.get(i);
ejecutar = true;
if (ejecutar) {
st = null;
st = conn.createStatement();
res = st.executeUpdate(cadenaSQL);
if (res == Statement.EXECUTE_FAILED) {
System.out.println("HA FALLADO LA CONSULTA " + cadenaSQL);
}
}
}
st.executeUpdate("SET FOREIGN_KEY_CHECKS=1");
st.close();
fichero.close();
commit();
desconectar();
fichero = null;
return true;
} catch (Exception ex) {
ex.printStackTrace();
rollback();
desconectar();
return false;
}
}
FileSQLCommandManager is a class that fills the ArrayList. This works, the ArrayList content is all right. It stops on executeUpdate of any query (not always, sometimes it works without problems WITH THE SAME SQL FILE).
First I disable the foreign key checks because it can drop a table with a reference (the order of recreation of tables is set by the SQL dump).
Any hint?
Thank's; I'm getting mad with this :(
Why are you going through all that work, when a simple mysql < db_backup.dump will restore the whole thing for you?
this really work for restore
String comando = "C:\\MySQL\\bin\\mysql.exe --host=localhost --port=3306 --user=root --password=123 < D:\\back.sql";
File f = new File("restore.bat");
FileOutputStream fos = new FileOutputStream(f);
fos.write(comando.getBytes());
fos.close();
Process run = Runtime.getRuntime().exec("cmd /C start restore.bat ");
and for backup
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.forLanguageTag("ru"));
java.util.Date currentDate = new java.util.Date();
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime.exec("C:\\MySQL\\bin\\mysqldump.exe --default-character-set=utf8 -uroot -p123 -c -B shch2 -r " + "D:/" + dateFormat.format(currentDate) + "_backup" + ".sql");
//change the dbpass and dbname with your dbpass and dbname
int processComplete = p.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully!");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception e) {
e.printStackTrace();
}
but you need to convey the exact path to mysql.exe and mysqldump.exe