I made this code and it gives the following 3 errors! I need help to get away with these errors that are there in the attached image. The 3 errors that are arising aren't going away since i don't have much info about how to include system commands.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EventListeners extends Applet
implements ActionListener{
public void init(){
Button b = new Button("Ping");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent e){
runSystemCommand(String command)
{try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}}
catch (Exception e) {
e.printStackTrace();
}}
public static void main(String[] args) {
String ip = "google.com";
runSystemCommand("ping " + ip);
}
}
![Errors][1]
You seem to be trying to write a function within a method. This is illegal in Java
Place you runSystemCommand method out side the actionPerformed method
public void actionPerformed(ActionEvent e) {
// Call runSystemCommand(...);
}
public void runSystemCommand(String command) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Some caveats...
Applets run in a tight security sandbox. It will NOT allow you to run system commands. Even if it, you could possible be running on a Linux or Mac box instead of Windows.
If you want to start with GUI program, start with something like JFrame, much easier to work with
I would also suggest getting your hands on a suitable IDE
Related
This is my main class, wherein run(), I am calling one another method install setup() which is for exe files.
public static void main(String[] args) {
launch(args);
}
public void startSetup() {
Runnable task=new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
installSetup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread=new Thread(task);
thread.start();
}
Here is my installsetup() method
public void installSetup() {
try {
Runtime.getRuntime().exec("cmd /c C:path\\setup.exe", null, new File("C:pathfolder\\01_Setupexe"));
//process.waitFor();
} catch (IOException e) {
e.printStackTrace();
}
};
I am calling it in my controller class like this:
public class Controller extends Thread {
#FXML
private ComboBox<?> dsetup;
public void generateRandom() {
if(dsetup.getValue()!=null) dsetupValue = dsetup.getValue().toString();
if(dsetupValue!=null)call.startSetup();
Before I was just calling the install files with the exec method but not with threads concept, the application was working fine, but it was executing all the.exe files at once and then my interface freezes. So now I am using threads concept and trying to implement one thread at a time. I don't understand if it is a wrong way or not, but I do not get any error in console.
Runtime.exec has been obsolete for many years. Use ProcessBuilder instead:
ProcessBuilder builder = new ProcessBuilder("C:\\path\\setup.exe");
builder.directory(new File("C:pathfolder\\01_Setupexe"));
builder.inheritIO();
builder.start();
The inheritIO() method will make the spawned process use the Java program’s stdin, stdout, and stderr, so it will not hang waiting for input or waiting for an available output buffer.
I doubt you need the new Thread or the sleep call, but I don’t know what files you’re calling or whether they depend on each other.
Sadly exec has some pitfalls. Most of the time using the process aproche (see Listing 4.3) saved me related to buffer issues and so on.
https://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html
import java.util.*;
import java.io.*;
public class MediocreExecJavac
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
Source: javaworld
I have a (Windows) command-line application that, when launched, prompts you to enter a password and then prints some text. Unfortunately, I do not own the source to the application and the application does not take any arguments when you launch it (i.e., cannot pass the password in when you start the application). I need to programmatically launch the application in Java and send a password to it and then read the response. While I have had success launching other programs (that just have output), I cannot seem to capture any output from this application. Here is my Java code:
import java.io.IOException;
import java.io.InputStream;
import java.lang.ProcessBuilder.Redirect;
public class RunCommand {
public static void main(String[] args) throws Exception {
new RunCommand().go();
}
void go() throws Exception {
ProcessBuilder pb = new ProcessBuilder("executable.exe");
pb.redirectErrorStream(true); // tried many combinations of these redirects and none seemed to help
pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process process = pb.start();
final Thread reader = new Thread(new Runnable() {
#Override
public void run() {
try {
final InputStream is = process.getInputStream();
int c;
while ((c = is.read()) != -1) {
// never gets here because c is always = -1
System.out.println((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
reader.start();
boolean cont = true;
while (cont) {
// force this to continue so we can try and get something from the input stream
}
process.destroyForcibly();
}
}
I'm working on a project and I would like to execute programs in the windows console or a linux terminal.
Instead of launching a new console and working the program in it I want to do something like the following:
rt.exec("cmd.exe /c start cmd.exe /k ruby rubycode.rb");
From this point on I want the user to be able to work with the program from the GUI/my program. The idea in my min is starting cmd in silent mode where it is not visible and latching on to it. Then redirecting the console output to the GUI and letting the user input data to the console through the GUI.
A similar concept is what most IDEs like jgrasp do. When you run a program you interface with it though their own command prompt.
How is this done? Iv'e tried grabbing the IOStreams from the process and trying to atleast print what the console outputs but no luck.
Here is an example:
public class ProcessTest {
private Process p;
private BufferedReader reader;
private BufferedWriter writer;
public void start() throws IOException {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
pb.directory(new File("./"));
this.p = pb.start();
this.reader = new BufferedReader(new InputStreamReader(this.p.getInputStream()));
this.writer = new BufferedWriter(new OutputStreamWriter(this.p.getOutputStream()));
new Read(this.reader).start();
}
public boolean writeToConsole(String s) throws IOException {
if (p == null)
return false;
this.writer.write(s + "\n");
this.writer.flush();
return true;
}
public class Read extends Thread {
private BufferedReader reader;
public Read(BufferedReader reader) {
this.reader = reader;
}
public void run() {
try {
String line;
while ((line = this.reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
new ProcessTest().start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
With the writeToConsole method you can write any string to the programm that you executed.
I'm writing a program that will run continuously and I was wondering if there was a Java equivalent to the Autoit SetHotKey(Key, Action()). I saw an answer on here that related to a GUI interface, but my program does not have a GUI. I just want the program to exit whenever I press a certain key, preferably ESC.
I'd have the program running in an infinite loop using the awt.Robot's keyevents, I'd like to be able to quit the program by pressing a certain key.
There are no core Java solutions since Java was built to be as operating system agnostic as possible, and to achieve your goal, you need a program that can integrate closer to the OS. The main solutions that I know of are to integrate your program to the OS via JNA, JNI, or (my favorite), AutoIt. Of done something similar by simply having my Java program and AutoIt communicate through standard IO and sockets.
A simple example:
Java program, TrialAutoIt3a.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class TrialAutoIt3a {
// ***** of course your path to program will be different
private static final String AUTOIT_PATH = "C:/Users/Pete/Documents/Programming/AutoIt/Experiment/";
private static final String AUTOIT_EXEC = "TestWithJava.exe";
protected static final CharSequence EXIT = "exit";
private static Process proc = null;
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("Type \"exit\" to exit program");
try {
proc = rt.exec(AUTOIT_PATH + AUTOIT_EXEC);
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
InputStream iStream = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(iStream);
final BufferedReader bufReader = new BufferedReader(isr);
OutputStream oStream = proc.getOutputStream();
final PrintWriter pw = new PrintWriter(oStream, true);
Runnable bufReaderRunnable = new Runnable() {
public void run() {
String output;
try {
while ((output = bufReader.readLine()) != null) {
System.out.println(output);
if (output.toLowerCase().contains(EXIT)) {
proc.destroy();
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(bufReaderRunnable).start();
Runnable myRun = new Runnable() {
public void run() {
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
pw.println(line);
}
scan.close();
}
};
new Thread(myRun).start();
}
}
AutoIt program, TestWithJava.au3:
Local $line = ""
While (True)
$line = $line & ConsoleRead()
If StringInStr($line, #CR) Or StringInStr($line, #LF) Then
ConsoleWrite($line & "to java" & #CRLF)
$line = ""
EndIf
Sleep(25)
WEnd
The AutoIt program will be compiled to an exe file prior to running this program
How to check the status of the windows services from a java program?
on the following example you can find how can you check windws service status and you can parsed to do certain action
import java.util.*;
import java.sql.*;
import java.io.*;
import java.text.*;
public class doscmd
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("sc query browser");
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
if(line.trim().startsWith("STATE"))
{
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("1"))
System.out.println("Stopped");
else
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("2"))
System.out.println("Startting....");
else
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("3"))
System.out.println("Stopping....");
else
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("4"))
System.out.println("Running");
}
line=reader.readLine();
}
}
catch(IOException e1) { }
}
}
At the very least you should be able to launch a cmd.exe process with the command sc query service-name and parse the output to determine the status. Not pretty, but lacking a Java API to the Windows service manager this would be a viable alternative.
EDIT - Read the Javadoc for java.lang.ProcessBuilder, which will allow you to execute an external command. You should probably set the redirectErrorStream property so that you don't have to handle two input streams (stdout and stderr), making for a much simpler design.
This method will return true or false depending upon service is running or not.
public boolean checkIfServiceRunning(String serviceName) {
Process process;
try {
process = Runtime.getRuntime().exec("sc query " + serviceName);
Scanner reader = new Scanner(process.getInputStream(), "UTF-8");
while(reader.hasNextLine()) {
if(reader.nextLine().contains("RUNNING")) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}