I need to execute a bat file that executes a PostgreSQL query in commandline using psql.exe in windows 10 and Java-8 .I have to execute the query through bat file only for testing the bat file. Below is the contents of the bat file
BatFileContents:
postgresql\bin\psql.exe -U username -p dbport -h 127.0.0.1 -c "
insert into table1 values(value1,value2);
insert into table2 values(value1,value2);
insert into table3 values(value1,value2) database"
I tried using java ProcessBuilder to call the bat file but pgsql is asking for password.Below is the code i used to call the bat file and provide password but it doesn't work as expected.
Code:
Main class:
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class ProcessTest {
public static void main(String args[])
{
Process process=null;
String batFile="\"c:\\batfilepath\\test.bat\"";
ProcessBuilder processBuilder=new ProcessBuilder(batFile);
try {
//process=Runtime.getRuntime().exec(batFile);
process=processBuilder.start();
StreamEater inputStreamEater=new StreamEater(process.getInputStream());
StreamEater errorStreamEater=new StreamEater(process.getErrorStream());
inputStreamEater.start();
errorStreamEater.start();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
writer.write("password");
writer.newLine();
writer.close();
int errorcode=process.waitFor();
System.out.println("errorcode:"+errorcode);
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
StreamEater class
class StreamEater extends Thread
{
private InputStream inputStream=null;
public StreamEater(InputStream stream)
{
this.inputStream=stream;
}
public void run()
{
System.out.println("Stream Eater thread started");
Scanner scanner=new Scanner(new InputStreamReader(inputStream));
String message="";
StringBuilder sb=new StringBuilder("");
try
{
System.out.println("before reading message");
while(scanner.hasNextLine())
{
message=scanner.nextLine();
sb.append(message);
sb.append("\n");
}
scanner.close();
System.out.println("after reading message "+sb.toString());
}
catch(Exception exception)
{
exception.printStackTrace();
}
System.out.println("Stream Eater thread ended");
}
}
Can anyone point out what mistake i have done.Is there any other way to send input to the bat file.