Java new ProcessBuilder("gcc", "--version").start() does not print out results [duplicate] - java

This question already has answers here:
Run cmd commands through Java
(14 answers)
Closed 10 months ago.
I want to run some commands from Java, but the following program does not print out the expected result. Any ideas?
import java.io.IOException;
public class MyClass {
public static void main(String args[]) throws IOException {
Process p = new ProcessBuilder("gcc", "--version").start();
}
}

You need to set the source and destination for subprocess standard I/O to be the same as those of the current Java process. You can to this by calling:
ProcessBuilder.inheritIO();
So your example should look something like:
import java.io.IOException;
public class MyClass {
public static void main(String args[]) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("gcc", "--version");
processBuilder.inheritIO();
processBuilder.start()
}
}
For advanced process I/O usage you should take a look at ProcessBuilder and Process JavaDocs.

Related

Null pointer exception when trying to use getResourceAsStream() function [duplicate]

This question already has answers here:
Java: NullPointerException from class.getResource( ... )
(5 answers)
InputStream.getResourceAsStream() giving null pointer exception
(7 answers)
Closed 1 year ago.
I am relatively new to Java, and as a learning experience, tried to build a classifier in java by reading a dataset from a file called "dataset.csv"
This is the code I wrote for the whole class:
import java.io.IOException;
import weka.classifiers.trees.J48;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.converters.CSVLoader;
import weka.core.Instances;
public class classifier {
public static final String DATASET = "dataset.csv";
public static Instances getData(String filename) throws IOException
{
CSVLoader loader = new CSVLoader();
loader.setSource(classifier.class.getResourceAsStream("/"+filename));
System.out.println("getData function running");
Instances dataset = loader.getDataSet();
return dataset;
}
public static void J48Classifier() throws Exception
{
Instances dataset = getData(DATASET);
Classifier j48 = new J48();
j48.buildClassifier(dataset);
Evaluation eval = new Evaluation(dataset);
eval.evaluateModel(j48,dataset);
System.out.println("Evaluation with dataset: ");
System.out.println(eval.toSummaryString());
System.out.println("Expression as per the algorithm: ");
System.out.println(j48);
System.out.println(eval.toMatrixString());
System.out.println(eval.toClassDetailsString());
}
public static void main(String args[]) throws Exception
{
J48Classifier();
}
}
But once I run the code, I am getting this error:
This is my file Structure for reference (the dataset.csv file is located in the src directory of the below cited image):
Can anyone help me figure out if I have missed out on something?

How to pipe input from a Java program to another using Bourne Shell

I have two simple Java programs and I want to pipe the result of the "Test" to the "Test2".
public class Test{
public static void main(String args[]){
System.out.println("Hello from Test");
}
}
and
public class Test2{
public static void main(String args[]){
System.out.printf("Program Test piped me \"%s\"",args[0]);
}
}
After I compiled both of .java files I tried to run the pipe command from terminal
java Test | java Test2, but I get an ArrayIndexOutOfBoundsException which means that the args array is not initialized?
How can the Test2 application take the outputstream value that Test.main() produced through piping?
One way is to use xargs:
java Test| xargs -I ARGS java Test2 ARGS
Pipes connect one program’s standard output to another program’s standard input, not to the other program’s command-line arguments.
The second class will not get the piped output as arguments to its main method; it will get the piped output as its standard input. So you want to read the information from System.in:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Test2 {
public static void main(String args[])
throws IOException {
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
stdin.lines().forEachOrdered(
line -> String.format("Program Test piped me \"%s\"", line));
}
}

How to execute if statement using Jython

import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1:");
interp.exec(" print('in if statement!'");
}
}
I need to be able to execute Python code from a Java program, so decided to try out Jython, but I'm unfamiliar with it. I tried executing the above code, but got the error: "Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))". Any ideas what this means or how I can otherwise execute an if statement using the PythonInterpreter?
Conditionals must be entered as a single string and you have an extra parenthesis:
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1: print 'in if statement!'");
}
}
Rather than executing a script line by line with strings you can invoke the interpreter to run a file. All you have to do is provide a file path to your python file, in this example place script.py in the src folder.
script.py
if 2 > 1:
print 'in if statement'
JythonTest.java
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("src/script.py");
}
}

How I can use CMD Command in Java program?

I want to use cmd Commands in java program,
Want to crope all images in folder, I downlaoded ImageMagick, and using cmd commands Its working 1 image,
cd C:\Users\Robert\Java-workspace\Crop_test\Crop_test1
cd convert -crop 312x312+0-10 image1.jpg new_image1.jpg
But, I want to use this in Java so, I can crop all images in folder by program, Here is my java program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.OutputStream;
public class test1 {
public static void main(String argv[]) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "C:\\Users\\Robert\\Java-workspace\\Crop_test\\Crop_test1\\", "convert -crop 312x312+0-10 image1.jpg new_image1.jpg");
Process p = pb.start();
p.waitFor();
}
}
Although you are asking how to use CMD and this was addressed on other answers I think that the best solution (considering your explanation of your implementation) would be to use a ImageMagick wrapper for Java as you can see here.
Cheers
You can invoke CMD commands as follows in Java;
Runtime.getRuntime().exec(your_command);
Best thing for you to do is to creat a batch file with the commands you need to run and then invoke your batch file using the following command;
Runtime.getRuntime().exec("cmd /C start D:\\test.bat");
because you cannot do any change directory commands using the Runtime class. Please try this option and let me know if you face any other issues.
A couple of things to try (both of which are untested):
Put a cd in the command line and use && to run both commands in one line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.OutputStream;
public class test1 {
public static void main(String argv[]) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cd C:\\Users\\Robert\\Java-workspace\\Crop_test\\Crop_test1\\ && convert -crop 312x312+0-10 image1.jpg new_image1.jpg");
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
}
}
Change the directory that the ProcessBuilder starts in:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.OutputStream;
public class test1 {
public static void main(String argv[]) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "convert -crop 312x312+0-10 image1.jpg new_image1.jpg");
pb.directory(new File("C:\\Users\\Robert\\Java-workspace\\Crop_test\\Crop_test1\\"));
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
}
}
Incidentally, are you sure you want to import org.omg.CORBA.portable.OutputStream? Did you mean java.io.OutputStream instead?
EDIT: if things still aren't working, then the next step is to see whether the problem is that convert isn't being found. Let's just run convert on its own without any arguments and see if it spits out its usage message to standard output. Run the following:
public class test1 {
public static void main(String argv[]) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "convert");
pb.redirectErrorStream(true);
Process p = pb.start();
StreamGobbler g = new StreamGobbler(p.getInputStream(), "OUT");
g.start();
p.waitFor();
}
}
Use the StreamGobbler class here. Does this print out convert's usage method, with each line prefixed with OUT>?

In Java I need to run a local method (code below)

Hey I have been trying to get the main to run the methods but I don't remember how to do it.
It is a simple program so far because I just started on it 15 minutes ago.
`
import java.awt.Robot;
import javax.swing.JFrame;
import java.lang.*;
import java.io.*;
public class sweetRevenge {
public static void main(String[] args) {
//call local static classes browserjacker and wallpaperjacker
start(browserJacker(1));
}
public static void browserJacker(int i)throws IOException{
try
{
//include bad things along with self made video of hacking linked to youtube
Process p=Runtime.getRuntime().exec("cmd /c start http://www.google.com");
}
catch(IOException e1) {System.out.println(e1);}
}
public static void wallpaperJacker (String args []) throws IOException {
Process p=Runtime.getRuntime().exec("cmd /c start");
}}
`
since your method is throwing an exception so the place where you will call it MUST have an exception handling mechanism, and your code needs to be modified.
import java.awt.Robot;
import javax.swing.JFrame;
import java.lang.*;
import java.io.*;
public class sweetRevenge {
public static void main(String[] args) {
//call local static classes browserjacker and wallpaperjacker
try{
browserJacker(); // will start method browserJacker
// since the method is static so it can be easily accessed from static method
}catch{IOException ex}{
}
}
public static void browserJacker()throws IOException{
//include bad things along with self made video of hacking linked to youtube
Process p=Runtime.getRuntime().exec("cmd /c start http://www.google.com");
}
public static void wallpaperJacker () throws IOException {
Process p=Runtime.getRuntime().exec("cmd /c start");
}
}

Categories

Resources