Windows cmd-output (Java) - java

I've found this topic, but the code doesn't work for me... Return Windows cmd text from Java?
After pressing a button I want to execute a batch-file, for testing purposes it's just the ipconfig-command.
The cmd-output should be written into a JTextFiled, but all I get is no text...
Here the code for writing it into the JTextField:
btnLock.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String g = "";
try {
Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream s = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;
try {
while ((temp = in.readLine()) != null)
{
System.out.println(temp);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLock.setBounds(10, 68, 89, 23);
contentPane.add(btnLock);
So what do I do wrong?
It's my first project with cmd-input, so please don't get mad cause of silly mistakes I made. ;)
Thx

Try the exec command that just takes a String parameter. The following test code worked on my system (though I was only printing to console, not to textfield):
BufferedReader in = null;
try{
Process p = Runtime.getRuntime().exec("ipconfig");
InputStream s = p.getInputStream();
in = new BufferedReader(new InputStreamReader(s));
String temp;
while ((temp = in.readLine()) != null) {
System.out.println(temp);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (in != null) in.close();
}
Also your code in the original post is also using a System.out.println. As far as I'm aware, you can't print to a JTextField using System.out.println.... You'd have to use the setText method.

If I run
ipconfig ""
I get
** Error: unrecognized or incomplete command line.**
You can only run from Java, commands which work on the command line.
BTW: If you are looking for errors, you need to read the error stream.

I would Runtime.getRuntime().exec(new String[] {"ipconfig > temp.txt"}); and then just read it as a text file using a BufferedReader.
I hope this helps.

Related

Python output not displayed in jar file

I have created a java gui which takes values from the user send it to python file for processing and then displays the output from the python file onto the java gui. This is working perfectly on eclipse but when i exported it into a jar file the output is not displayed. I've seen a bunch of other questions like this but they do not give a solution that would help me.
This is how i connect my python script to java.
public void connection(String name)
{
ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie_name",name);
///System.out.println("running file");
Process process = null;
try {
process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int err = 0;
try {
err = process.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("any errors?"+(err==0 ? "no" : "yes"));
/* try {
System.out.println("python output "+ output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
matches.setText(output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br= new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
//descp.setText("<html><br/><html>");
//sb.append("\n");
}
}
finally
{
br.close();
}
return sb.toString();
}

Pulling Computer Name from Batch File

I have a method that allows me to type part of the computer name into a jtextfield and I submit via jbutton. The cmd prompt successfully gives me the full computer name. So if I typed 111255 the command prompt will output coud111255. Query I'm using (#dsquery computer -name *%1)
This part works great. My issue is pulling the full computer name out of the batch file and assigning it to a java variable. I'm trying to append the full computer name to textArea, but it is only pulling the hardcoded value from here:
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";)
Any Suggestions on how to get the full computer name appended to textArea?
sendParam() passes half of computer name into batch script to find full computer name.
public static void sendParam(){
try{
String val = MISControlPanel.textField.getText(); //Put whatever you want to pass as a prefix in place of "Computer"
jLabel1.setText(val);
Process p ;
p = Runtime.getRuntime().exec("cmd /c start c:\\computerQuery.bat "+val+"");
}
catch(Exception e){
e.printStackTrace();
}
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
//textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
textArea.append(String.format(" %s%n", commonName));
//textArea.setText(ComputerQuery.val);
selectedComputerFromAD.setText(commonName);
selectedComputerFromAD.setFont(new Font("Tahoma", Font.BOLD, 14));
selectedComputerFromAD.setForeground(Color.RED);
selectedComputerFromAD.setBounds(349, 84, 102, 19);
frame.getContentPane().add(selectedComputerFromAD);
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});

Executing imagemagick commands with java gives no output

I am writing a java aplication that edits images using imagemagick commands;
However, the comands do not work and I am getting no output from them;
Actually, the comand identify is not recognized and I get CreateProcess error=2;
This seems odd, because the imagemagick instalation folder is included in my Path variable.
Here's my code:
public class Test {
public static void main(String argv[]) {
Runtime ru = Runtime.getRuntime();
Process p = null;
try {
//I've added this as a bouns, this should not be neccessary(methinks)
String[] s = {"C:\\Program Files\\ImageMagick-6.8.6-Q16"};
String[] cmd = {"convert", "acc-logo.jpg","-flip", "edited.jpg"};
p = ru.exec(cmd,s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader ina = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
try {
while ((line = ina.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a space in the path to the executable, and the Runtime.exec() call is having problems with it. Use ProcessBuilder instead; it handles spaces in arguments much more easily.

Run a .dmg file through java code

How can I mount a .dmg file through java code under OS X?
This will work (but only on OS X):
try {
String[] command = {"/usr/bin/hdiutil", "attach", "/Users/path/to/your.dmg"};
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DMGs are not executables, are apple diskimages
reference is here
thus you can't "run" it.
You can use a Process, of course. But it won't work anywhere except on a Mac.
Saying that is like asking how to run an ISO file through Java. You simply can't; it's a disk image.

How to remove a line from a file by knowing its position?

I want to remove a line from my file (specifically the second line)
so I have used another file to copy in it ,but using the following code the second file contain exactly the same text.(My original file .txt and my final file .xml)
public static File fileparse() throws SQLException, FileNotFoundException, IOException {
File f=fillfile();//my original file
dostemp = new DataOutputStream(new FileOutputStream(filetemp));
int lineremove=1;
while (f.length()!=0) {
if (lineremove<2) {
read = in.readLine();
dostemp.writeBytes(read);
lineremove++;
}
if (lineremove==2) {
lineremove++;
}
if (lineremove>2) {
read = in.readLine();
dostemp.writeBytes(read);
}
}
return filetemp;
}
You do not read the line if the lineremove is 2 and also you check if it is greater than 2 after you increased it when it was 2. Do it like this:
int line = 1;
String read = null;
while((read = in.readLine()) != null){
if(line!=2)
{
dostemp.writeBytes(read);
}
line++;
}
you can use BufferedReader with the readLine() method to read line by line, check if it a line you want and skip the lines you dont want.
check the docs at: BufferedReader
here is a working example (Not the most beautiful or clean :) ):
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("d:\\test.txt"));
} catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
PrintWriter out = null ;
try {
out = new PrintWriter (new FileWriter ("d:\\test_out.txt"));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String line = null;
int lineNum = 0;
try {
while( (line = in.readLine()) != null) {
lineNum +=1;
if(lineNum == 2){
continue;
}
out.println(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out.flush();
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories