Java to batch file - java

try {
String comd ="E:/ior1.txt";
Runtime rt = Runtime.getRuntime();
rt.exec("C:/tes1.bat"+comd+"");
System.out.println("Process exitValue: ");
}
catch (Exception e)
{
System.out.println("Unexpected exception Trying to Execute Job: " +e);
}
But when I run I get an exception like this
Unexpected exception Trying to Execute Job: java.io.IOException: CreateProcess:
C:/tes1.batE:/ior1.txt error=2
Press any key to continue . . .
This is the batch file content
echo "testing"
echo %1

There's a blank missing after .bat (in the rt.exec line)
Edit:
You could also try executing:
rt.exec("cmd /c c:/tes1.bat "+comd);

Try prefixing the exec call with cmd /c or call, e.g.
rt.exec("cmd /c c:/tes1.bat "+comd);
(I don't have a Windows box available right now so I can't test this but as far as I remember, launching batch files required launching the command interpreter first.)

When i see this correct, you have to put a space between the bat command and the argument
EDIT:
try {
String comd ="E:/ior1.txt";
Runtime rt = Runtime.getRuntime();
rt.exec("C:/tes1.bat "+comd+"");
System.out.println("Process exitValue: ");
}
catch (Exception e)
{
System.out.println("Unexpected exception Trying to Execute Job: " +e);
}
EDIT 2:
After taking a look again and testing on my PC the other answers seems correct. The cmd is missing.
rt.exec("cmd /c c:/tes1.bat "+comd);

Be aware, that there is a number of issues related to executing an external process from within your Java program if you have to use this in a production environment.
You have e.g. to be aware of the fact, that if the output from the process is larger than the buffer used by the JVM<->OS the exec will block forever.
I normally use a wrapper with Threads to read from the buffers.
Its not perfect, but something like (see main() for details on usage):
/**
* Executes a given OS dependent command in a given directory with a given environment.
* The parameters are given at construction time and the initialized object is immutable.
* After the object initialization and execution of the blocking exec() method the state
* can't be changed. The result of the execution can be accessed through the get methods
* for the exitValue, stdOut, and stdErr properties. Before the exec() method is completed
* the excuted property is false and the result of other getters is undefined (null).
*/
public class CommandExecutor {
/**
* Specifies the number of times the termination of the process is
* waited for if the OS gives interruptions
*/
public static final int NUMBER_OF_RUNS = 2;
/**
* Used for testing and as example of usage.
*/
public static void main(String[] args) {
System.out.println("CommandExecutor.main Testing Begin");
String command_01 = "cmd.exe /C dir";
File dir_01 = new File("C:\\");
System.out.println("CommandExecutor.main Testing. Input: ");
System.out.println("CommandExecutor.main Testing. command: " + command_01);
System.out.println("CommandExecutor.main Testing. dir: " + dir_01);
CommandExecutor ce_01 = new CommandExecutor(command_01, null, dir_01);
ce_01.exec();
System.out.println("CommandExecutor.main Testing. Output:");
System.out.println(" exitValue: " + ce_01.getExitValue());
System.out.println(" stdout: " + ce_01.getStdout());
System.out.println(" stderr: " + ce_01.getStderr());
String command_02 = "cmd.exe /C dirs";
File dir_02 = new File("C:\\");
System.out.println("CommandExecutor.main Testing. Input: ");
System.out.println("CommandExecutor.main Testing. command: " + command_02);
System.out.println("CommandExecutor.main Testing. dir: " + dir_02);
CommandExecutor ce_02 = new CommandExecutor(command_02, null, dir_02);
ce_02.exec();
System.out.println("CommandExecutor.main Testing. Output:");
System.out.println(" exitValue: " + ce_02.getExitValue());
System.out.println(" stdout: " + ce_02.getStdout());
System.out.println(" stderr: " + ce_02.getStderr());
System.out.println("CommandExecutor.main Testing End");
}
/*
* The command to execute
*/
protected String command;
/*
* The environment to execute the command with
*/
protected String[] env;
/*
* The directory to execute the command in
*/
protected File dir;
/*
* Flag set when the command has been executed
*/
protected boolean executed = false;
/*
* Exit value from the OS
*/
protected int exitValue;
/*
* Handle to the spawned OS process
*/
protected Process process;
/*
* Std error
*/
protected List<String> stderr;
/*
* Worker Thread to empty the stderr buffer
*/
protected Thread stderrReader;
/*
* Std output
*/
protected List<String> stdout;
/*
* Worker Thread to empty the stdout buffer
*/
protected Thread stdoutReader;
/**
* Creates a new instance of the CommandExecutor initialized to execute the
* specified command in a separate process with the specified environment
* and working directory.
*
* #param env
*/
public CommandExecutor(String command, String[] env, File dir) {
this.command = command;
this.env = env;
this.dir = dir;
}
/**
* Creates a reader thread for the stderr
*/
protected void connectStderrReader() {
stderr = new ArrayList<String>();
final InputStream stream = process.getErrorStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
stderrReader = new Thread(new Runnable() {
public void run() {
String nextLine = null;
try {
while ((nextLine = reader.readLine()) != null) {
stderr.add(nextLine);
}
} catch (IOException e) {
System.out.println(
"CommandExecutor.connectStderrReader() error in reader thread");
e.printStackTrace(System.out);
}
}
});
stderrReader.start();
}
/**
* Creates a reader thread for the stdout
*/
protected void connectStdoutReader() {
stdout = new ArrayList<String>();
final InputStream stream = process.getInputStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
stdoutReader = new Thread(new Runnable() {
public void run() {
String nextLine = null;
try {
while ((nextLine = reader.readLine()) != null) {
stdout.add(nextLine);
}
} catch (IOException e) {
System.out.println(
"CommandExecutor.connectStdoutReader() error in reader thread");
e.printStackTrace(System.out);
}
}
});
stdoutReader.start();
}
/**
* Creates the process for the command
*/
protected void createProcess() {
try {
process = Runtime.getRuntime().exec(command, env, dir);
} catch (IOException e) {
System.out.println("CommandExecutor.exec() error in process creation. Exception: " + e);
e.printStackTrace(System.out);
}
}
/**
* Executes command in a separate process in the specified directory. Method will block until
* the process has terminated. Command will only be executed once.
*/
public synchronized void exec() {
// Future enhancement: check for interrupts to make the blocking nature interruptible.
if (!executed) {
createProcess();
connectStdoutReader();
connectStderrReader();
waitForProcess();
joinThreads();
exitValue = process.exitValue();
executed = true;
}
}
/**
* #return the command
*/
public String getCommand() {
return command;
}
/**
* #return the dir
*/
public File getDir() {
return dir;
}
/**
* #return the env
*/
public String[] getEnv() {
return env;
}
/**
* #return the exitValue
*/
public int getExitValue() {
return exitValue;
}
/**
* #return the stderr
*/
public List<String> getStderr() {
return stderr;
}
/**
* #return the stdout
*/
public List<String> getStdout() {
return stdout;
}
/**
* #return the executed
*/
public boolean isExecuted() {
return executed;
}
/**
* Joins on the 2 Reader Thread to empty the buffers
*/
protected void joinThreads() {
try {
stderrReader.join();
stdoutReader.join();
} catch (InterruptedException e) {
System.out.println("CommandExecutor.joinThreads() error. Exception: ");
e.printStackTrace(System.out);
}
}
/**
* Creates a String representing the state of the object
*/
#Override
public synchronized String toString() {
StringBuilder result = new StringBuilder();
result.append("CommandExecutor:");
result.append(" command: " + command);
result.append(" env: " + Arrays.deepToString(env));
result.append(" dir: " + dir);
result.append(" executed: " + executed);
result.append(" exitValue: " + exitValue);
result.append(" stdout: " + stdout);
result.append(" stderr: " + stderr);
return result.toString();
}
/**
* Waits for the process to terminate
*/
protected void waitForProcess() {
int numberOfRuns = 0;
boolean terminated = false;
while ((!terminated) && (numberOfRuns < NUMBER_OF_RUNS)) {
try {
process.waitFor();
terminated = true;
} catch (InterruptedException e) {
System.out.println("CommandExecutor.waitForProcess() error");
e.printStackTrace(System.out);
numberOfRuns++;
}
}
}
}

Additonal to laalto's comment:
Runntime provides several signatures of exec().
rt.exec("cmd /c c:/tes1.bat "+comd);
rt.exec(new String[] {"cmd","/c","c:/tes1.bat",comd});

Related

virtual machine object cannot find or load Main class

so i have problem where i am trying to open a file through my own written virtual machine object in java but the problem is that the virtual machine is not running and causing an error.
Error: Could not find or load main class C:\Users\dell\Trace\Main.java
we also tried modifying the CLASSPATH & PATH with no success
below is the code of the main
import com.sun.jdi.Bootstrap;
import com.sun.jdi.connect.*;
import java.util.Map;
import java.util.List;
import java.util.Iterator;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Trace {
// Running remote VM
private final VirtualMachine vm;
// Thread transferring remote error stream to our error stream
private Thread errThread = null;
// Thread transferring remote output stream to our output stream
private Thread outThread = null;
// Mode for tracing the Trace program (default= 0 off)
private int debugTraceMode = 0;
// Do we want to watch assignments to fields
private boolean watchFields = false;
// Class patterns for which we don't want events
private String[] excludes = {"java.*", "javax.*", "sun.*",
"com.sun.*"};
/**
* main
*/
public static void main(String[] args) {
new Trace(args);
}
/**
* Parse the command line arguments.
* Launch target VM.
* Generate the trace.
*/
Trace(String[] args) {
PrintWriter writer = new PrintWriter(System.out);
int inx;
for (inx = 0; inx < args.length; ++inx) {
String arg = args[inx];
if (arg.charAt(0) != '-') {
break;
}
if (arg.equals("-output")) {
try {
writer = new PrintWriter(new FileWriter(args[++inx]));
} catch (IOException exc) {
System.err.println("Cannot open output file: " + args[inx]
+ " - " + exc);
System.exit(1);
}
} else if (arg.equals("-all")) {
excludes = new String[0];
} else if (arg.equals("-fields")) {
watchFields = true;
} else if (arg.equals("-dbgtrace")) {
debugTraceMode = Integer.parseInt(args[++inx]);
} else if (arg.equals("-help")) {
usage();
System.exit(0);
} else {
System.err.println("No option: " + arg);
usage();
System.exit(1);
}
}
if (inx >= args.length) {
System.err.println("<class> missing");
usage();
System.exit(1);
}
StringBuffer sb = new StringBuffer();
sb.append(args[inx]);
for (++inx; inx < args.length; ++inx) {
sb.append(' ');
sb.append(args[inx]);
}
vm = launchTarget(sb.toString());
generateTrace(writer);
}
/**
* Generate the trace.
* Enable events, start thread to display events,
* start threads to forward remote error and output streams,
* resume the remote VM, wait for the final event, and shutdown.
*/
void generateTrace(PrintWriter writer) {
vm.setDebugTraceMode(debugTraceMode);
EventThread eventThread = new EventThread(vm, excludes, writer);
eventThread.setEventRequests(watchFields);
eventThread.start();
redirectOutput();
vm.resume();
// Shutdown begins when event thread terminates
try {
eventThread.join();
errThread.join(); // Make sure output is forwarded
outThread.join(); // before we exit
} catch (InterruptedException exc) {
// we don't interrupt
}
writer.close();
}
/**
* Launch target VM.
* Forward target's output and error.
*/
VirtualMachine launchTarget(String mainArgs) {
LaunchingConnector connector = findLaunchingConnector();
Map arguments = connectorArguments(connector, mainArgs);
try {
return connector.launch(arguments);
} catch (IOException exc) {
throw new Error("Unable to launch target VM: " + exc);
} catch (IllegalConnectorArgumentsException exc) {
throw new Error("Internal error: " + exc);
} catch (VMStartException exc) {
throw new Error("Target VM failed to initialize: " +
exc.getMessage());
}
}
void redirectOutput() {
Process process = vm.process();
// Copy target's output and error to our output and error.
errThread = new StreamRedirectThread("error reader",
process.getErrorStream(),
System.err);
outThread = new StreamRedirectThread("output reader",
process.getInputStream(),
System.out);
errThread.start();
outThread.start();
}
/**
* Find a com.sun.jdi.CommandLineLaunch connector
*/
LaunchingConnector findLaunchingConnector() {
List connectors = Bootstrap.virtualMachineManager().allConnectors();
Iterator iter = connectors.iterator();
while (iter.hasNext()) {
Connector connector = (Connector)iter.next();
if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
return (LaunchingConnector)connector;
}
}
throw new Error("No launching connector");
}
/**
* Return the launching connector's arguments.
*/
Map connectorArguments(LaunchingConnector connector, String mainArgs) {
Map arguments = connector.defaultArguments();
Connector.Argument mainArg =
(Connector.Argument)arguments.get("main");
if (mainArg == null) {
throw new Error("Bad launching connector");
}
mainArg.setValue(mainArgs);
if (watchFields) {
// We need a VM that supports watchpoints
Connector.Argument optionArg =
(Connector.Argument)arguments.get("options");
if (optionArg == null) {
throw new Error("Bad launching connector");
}
optionArg.setValue("-classic");
}
return arguments;
}
/**
* Print command line usage help
*/
void usage() {
System.err.println("Usage: java Trace <options> <class> <args>");
System.err.println("<options> are:");
System.err.println(
" -output <filename> Output trace to <filename>");
System.err.println(
" -all Include system classes in output");
System.err.println(
" -help Print this help message");
System.err.println("<class> is the program to trace");
System.err.println("<args> are the arguments to <class>");
}
}

class not found exception in openshift

Am running this command below in a shell script, it works on windows but can't identify why its not working in the sheell script in openshift. I have the .class files in that folder.
export JARPATH=$(JARS=("$LIB"/*.jar); IFS=:; echo "${JARS[*]}")
nohup javac -classpath $JARPATH $MATCHFACES/*.java > ${OPENSHIFT_DIY_LOG_DIR}/compile.log 2>&1 &
// the above works without errors
cd $OPENSHIFT_REPO_DIR"src/matchfaces"
nohup java -classpath $JARPATH matchfaces.Listener > ${OPENSHIFT_DIY_LOG_DIR}/Listener.log 2>&1 &
// the above spits the error below
The error I get is
Error: Could not find or load main class .var.lib.openshift.586b985a89r3cfe9fa1111bc.app-root.runtime.repo.src.matchfaces.Listener
Listener.java source code
package matchfaces;
import Luxand.FSDK;
/**
*
* #author daviestobialexz
*/
public class Listener {
public static final String JAVABRIDGE_PORT = "1699";//8080
static final php.java.bridge.JavaBridgeRunner runner =
php.java.bridge.JavaBridgeRunner.getInstance(JAVABRIDGE_PORT);
/**
* #param args the command line arguments
* #throws java.lang.InterruptedException
*/
public static void main( String[] args ) {
// TODO code application logic here
try {
System.loadLibrary("facesdk");
int res = FSDK.ActivateLibrary("OYVHSxkUjwoYalZqg=");
FSDK.Initialize();
FSDK.SetFaceDetectionParameters(true, true, 384);
FSDK.SetFaceDetectionThreshold(5);
if (res == FSDK.FSDKE_OK) {
System.out.printf("FaceSDK activated", "FaceSDK activated\n");
} else {
System.out.printf("Error activating FaceSDK: ", res + "\n");
}
} catch (java.lang.UnsatisfiedLinkError e) {
System.out.printf("exception ", e.getMessage());
}
try{
runner.waitFor();
}catch(Exception ex){
System.out.printf("Error: ", ex.getMessage() + "\n");
}
// System.exit(0);
}
}

Why do I lose the console output?

I have this code in a JUnit Test :
public class CvsCommandTest {
...
#Test
public void test() {
PServerConnection con = new PServerConnection(root);
GlobalOptions globalOptions = new GlobalOptions();
globalOptions.setCVSRoot(root.toString());
Client client = new Client(con, new StandardAdminHandler());
client.setLocalPath(LOCAL_PATH);
client.getEventManager().addCVSListener(new BasicListener());
CheckoutCommand checkoutCmd = new CheckoutCommand();
checkoutCmd.setBuilder(null);
checkoutCmd.setModule("Outils");
try {
client.getConnection().open();
LOG.info("CVS checkout : " + checkoutCmd.getCVSCommand());
boolean successCheckout = client.executeCommand(checkoutCmd,globalOptions );
LOG.info("Checkout COMPLETED : " + successCheckout);
...
The output, while debugging, is :
[INFO] fr.package.CvsCommandTest - CVS checkout : checkout
-N Outils
cvs checkout: Updating Outils
The first line is my log, the second comes from the listener but I don't get the remaining of my logs.
The basicListener is defined this way :
import java.io.PrintStream;
import org.netbeans.lib.cvsclient.event.CVSAdapter;
import org.netbeans.lib.cvsclient.event.MessageEvent;
public class BasicListener extends CVSAdapter {
/** * Stores a tagged line */
private final StringBuffer taggedLine = new StringBuffer();
/**
* Called when the server wants to send a message to be displayed to the
* user. The message is only for information purposes and clients can choose
* to ignore these messages if they wish.
*
* #param e
* the event
*/
public void messageSent(MessageEvent e) {
String line = e.getMessage();
PrintStream stream = e.isError() ? System.err : System.out;
if (e.isTagged()) {
String message = MessageEvent.parseTaggedMessage(taggedLine, line);
if (message != null) {
stream.println(message);
}
} else {
stream.println(line);
}
stream.close();
}
}
What have I missed?
Turned comment in to answer
System.out stream.close(); --> good night...
Explanation:
Since he is using the System.out to output he's log message when he close the System.out #see end of public void messageSent(MessageEvent e) ,stream.close(); the System.out is closed and can not be used anymore, so good night to System.out
The solution is:
Removing the stream.close(); command

Why is there no output in my file after using Writer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to make a programme which does times tables and it outputs a to a file called log.txt as a log file, but when I run it all it does is runs though and does the times tables and makes the file, but writes nothing to the file. Can someone please tell me, what's wrong with my code? If you do, thanks.
Key:
[.jar = runnable file]
[.zip = source code]
Download links:- http://wardogsk93-ftp.bugs3.com/Downloads/Java/Counter/
Java Doc:- http://wardogsk93-ftp.bugs3.com/Downloads/Java/Counter/Java%20Doc/
Main.java:-
public class Main {
/************************************************/
/*************STUFF YOU CAN CHANGE***************/
/************************************************/
/** change this to start at a different number must be a number {#link Integer}**/
public static int minCount = 1;
/** change to change the number of where the programme will end must be a number {#link Integer}**/
public static int maxCount = 10;
/** change this to how many times you want to sleep for in seconds (1 = 1 second, 2 = 2 second, 10 = 10 second) before moving to next sum must be a number {#link Integer} **/
public static int sleepAmountMultiplyer = 1;
/** true = outputs to the command prompt / false = outputs to eclipse console {#link boolean}**/
public static boolean outputTOCMD = true;
/************************************************/
/******DONT CHANGE ANYTHING BELOW THIS LINE******/
/************************************************/
/** allows to output to a command prompt **/
private static Console cmd;
private static Output file;
private static int endNumber = maxCount + 1;
private static int sleepAmount = 1000 * sleepAmountMultiplyer;
/**
* main method
* call this to start
**/
public static void start() {
file = new Output();
if (outputTOCMD) {
cmd = new Console();
count();
cmd.exit();
} else {
count();
System.exit(1);
}
}
public static Main getInstance() {
return Main.getInstance();
}
/**code to start running**/
private static void count() {
try {
for (int i = minCount; i < maxCount + 1; i++) {
int j = i * i;
Thread.sleep(sleepAmount);
if (i == endNumber) {
return;
}
if (outputTOCMD) {
cmd.out(i + " X " + i + " = " + j);
file.write(String.valueOf(i) + " X " + String.valueOf(i) + " = " + String.valueOf(j));
} else {
System.out.println(i + " X " + i + " = " + j);
file.write(String.valueOf(i) + " X " + String.valueOf(i) + " = " + String.valueOf(j));
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output.class:-
import java.io.*;
public class Output {
public Output() {}
private Console cmd;
private File logFile;
private String input;
private BufferedReader reader;
private BufferedWriter writer;
public Output(Console cmd, File logFile, BufferedReader reader, BufferedWriter writer) {
this.cmd = cmd;
this.logFile = logFile;
this.reader = reader;
this.writer = writer;
}
/** writes to a log file using {#link FileWriter} **/
public void write(String message) {
try {
logFile = new File("log.txt");
writer = new BufferedWriter(new FileWriter(logFile));
if (!logFile.exists()) {
writer.write(message);
writer.close();
} else {
read();
if (logFile.isFile()) {
logFile.delete();
writer.write(message);
}
}
} catch (IOException e) {
if (Main.outputTOCMD) {
cmd.out(e.getMessage());
} else {
e.printStackTrace();
}
}
}
/** writes to a log file using {#link FileReader} **/
public void read() {
try {
logFile = new File("log.txt");
reader = new BufferedReader(new FileReader(logFile));
if (logFile.exists()) {
setInput(reader.readLine());
}
} catch (IOException e) {
if (Main.outputTOCMD) {
cmd.out(e.getMessage());
} else {
e.printStackTrace();
}
}
}
/**
* #return the input
*/
private String getInput() {
return input;
}
/**
* #param input the input to set
*/
private String setInput(String input) {
this.input = input;
return input;
}
}
Console.class:-
import java.awt.Color;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
/**
* Creates the command prompt window in class {#link Console}
*/
public class Console {
private JFrame frame;
private JTextArea console;
private Image icon;
public Console() {
try {
frame = new JFrame();
frame.setBackground(Color.BLACK);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setName("Commad Prompt");
frame.setSize(678, 340);
frame.setTitle(frame.getName());
frame.setVisible(true);
icon = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/en/e/ef/Command_prompt_icon_(windows).png")).getImage();
frame.setIconImage(icon);
console = new JTextArea();
console.setAutoscrolls(true);
console.setBackground(Color.BLACK);
console.setEditable(false);
console.setForeground(Color.WHITE);
console.setSelectionColor(Color.WHITE);
console.setSelectedTextColor(Color.BLACK);
console.setVisible(true);
frame.add(console);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* #param {#link String} text does the same as {#link System}.out.println();
*/
public void out(String text) {
console.append(text + "\n");
}
/**
* #exception {#link Exception} to catch any errors and prints them to the window
* does the same has {#link System}.exit(1);
*/
public void exit() {
try {
Thread.sleep(1000 * Main.sleepAmountMultiplyer);
console.disable();
frame.dispose();
System.exit(1);
} catch (Exception e) {
this.out(e.getMessage());
}
}
/**
* #return Allows you to acces all the stuff in <br>{#link Console}</br>
**/
public Console getInstance() {
return this;
}
}
Launch File:-
public class Test {
public static void main(String[] args) {
Main.minCount = 1;
Main.maxCount = 10;
Main.sleepAmountMultiplyer = 1;
Main.outputTOCMD = true;
Main.start();
}
}
You must always use the close() method when finished writing to a file. Else wise it won't save it (you also want to close to avoid resource leak errors...read here). So in this method:
public void write(String message) {
try {
logFile = new File("log.txt");
writer = new BufferedWriter(new FileWriter(logFile));
if (!logFile.exists()) {
writer.write(message);
writer.close();
} else {
read();
if (logFile.isFile()) {
logFile.delete();
writer.write(message);
}
}
//close the buffer writer in order to save
writer.close();
} catch (IOException e) {
if (Main.outputTOCMD) {
cmd.out(e.getMessage());
} else {
e.printStackTrace();
}
}
}
Alternatively, you can close in a finally block. You must also close the BufferReader after you're done reading. You need to be very careful when using Thread if you plan to have multiple Thread reading/writing to same file.
NOTE: This will overwrite the file each time. However, if you want to append the data, change this line:
writer = new BufferedWriter(new FileWriter(logFile));
To:
writer = new BufferedWriter(new FileWriter(logFile, true));
The second parameter in FileWriter is confirming whether you want to overwrite the file or append to the file. Check out this example.

Reading output from java.lang.Process - There is nothing to read

I'm trying to execute terminal command in linux trough Java and i cant get any input from inputStream.
This is my code
ProcessBuilder build = new ProcessBuilder("/usr/bin/xterm", "find /home");
Process pr = null;
BufferedReader buf;
try {
build.redirectErrorStream(true);
pr = build.start();
buf = new BufferedReader(new InputStreamReader( pr.getInputStream()));
String line = buf.readLine();
pr.waitFor();
while (true) {
System.out.println(line + "sadasdas");
line = buf.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
Process is executed and immediately terminal closes, and no output is catched and printed. On the other hand if i will compose an unknown command i get all the lines with tips how to use commands. Same problem i had with windows cmd. I was trying to use getRuntime.exec(cmd) method but the end is the same.
I've also tried to created separate threads for process and reader which looks like this
public class kurdee
{
public static Thread thread;
public kurdee()
{
List cmd = new LinkedList();
cmd.add(new String("/usr/bin/xterm"));
cmd.add(new String("find"));
thisProc thispr = new thisProc(cmd);
this.thread = new Thread(thispr);
thread.start();
reader rd = new reader(thispr.proc);
Thread thread1 = new Thread(rd);
thread1.start();}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
kurdee kurd = new kurdee();
}
});
}
}
class reader implements Runnable
{
private BufferedReader buf;
private Process proc;
public reader(Process proc)
{
this.proc=proc;
this.buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
}
public void run()
{
String line="";
System.out.println("Thread is alive");
try{
//Thread.sleep(1000);
line = buf.readLine();
}catch(Exception ex){System.out.println(ex + " before first while started");}
while(kurdee.thread.isAlive())
{
System.out.println("Thread is alive");
while(line!=null)
{
try{
//System.out.println(proc.exitValue());
System.out.println(line + " asd");
line=buf.readLine();
}catch(Exception e){System.out.println(e + " Inner while loop");}
}
}
}
}
class thisProc implements Runnable
{
private ProcessBuilder build;
public static Process proc=null;
public thisProc(List<String> args)
{
this.build = new ProcessBuilder(args);
build.redirectErrorStream(true);
try{
this.proc = build.start();
}catch(Exception ex){System.out.println(ex + " proc class");}
}
public void run()
{
try{
proc.waitFor();
}catch(Exception ex){System.out.println(ex + " proc class");}
}
}
But with any combination of invoking threads etc i make there is still nothing to read.
I'm trying to use command "find /home -xdev -samefile file" to get all hard links to file so maybe there is an easier way.
xterm is not the way to execute processes in unix, it is not a shell. a shell is something like "/bin/sh". however, "find" is a normal unix executable, so you should just execute that directly, e.g. new ProcessBuilder("find", "/home"). and yes, you should always process the streams on separate threads, as recommended by this article.
First, don't try to execute the command with xterm, that's pointless; just do it directly. Secondly, be careful when you compose your array of command strings to put one word into each string; passing, for example "find /home" as a single string among many to ProcessBuilder is going to error out.

Categories