I need to execute .bat files in my java application. Suppose I have a text file with this sample content:
{
"id": 12,
"name": "test"
}
And in my .bat file, I have a command for outputing text file content. So this is my .bat file content:
#some other commands
more path\to\file.txt
And finally, this is my java code for executing this .bat file:
Process process = Runtime.getRuntime().exec("path\to\file.bat");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
List<String> outputs = new ArrayList<>();
while ((line = reader.readLine()) != null) {
outputs.add(line);
}
After executing this code, the outputs list has data something like this:
[...,
"{",
" "id": 12",",
" "name": "test",",
"}"
]
I means, this returns output line by line. But I want to have whole command output as one index of my list. In the other words, I want to have command by command instead of line by line output(every command has just one output).
Is this possible doing something like that?
Edit: I tried using ProcessBuilder also, but result was the same.
more path\to\file.txtin batch file, use insteadtype "path\to\file.txt"or read the text file with Java code. If you want to know the differences between the commandstypeandmore, open a command prompt, runtype /?, read the output help (very short) andmore /?and read again output short help.stdouta line likeecho NewCmdand in Java program concatenate everything between two"NewCmd"strings to one string with\nor\r\nbefore adding it to string arrayoutputsand of course discard the strings"NewCmd". But I am 100% sure, there are better solutions for the entire task.