I have created a OpenNotepad.bat file with text stating "C:\windows\system32" notepad.exe and saved it to my desktop. I have created a Java class. What do I have to type in the cmd to get that text from the .bat file?
Is there a specific command that I should use to get the command prompt to display that text?
Here is my Java code:
public class OpenBatchFile {
public OpenBatchFile() {
super();
}
public static void main(String[] args) {
//Get Runtime object
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("cmd /c start Desktop:\\OpenNotePad.bat");
}
catch (IOException e) {
System.out.println(e);
}
}
}
I am totally new to this. I referred to this tutorial:
Execute batch file from Java Code using Runtime class
When in cmd.exe console, type the command help which will display all possible commands you can run in a cmd prompt or batch... If you read through each, you will notice two that stand out:
MORE Displays output one screen at a time.
TYPE Displays the contents of a text file.
This will display the content of any file if you use them like:
type filename.txt
more filename.txt
or
type "c:\program files\some dir\filename.txt"
more "c:\program files\some dir\filename.txt"
Related
This Java programm opens a Batch file and passes the string folderName
public class FolderCreator {
public static void main(String[] args) {
try{
Process p = Runtime.getRuntime().exec("C:/Documents/NameFolder.bat folderName");
p.waitFor();
}catch(Exception e) {
System.out.println(e);
}
}
}
This is the NameFolder.bat file. It shall create a folder with the name from the passed Java variable above.
//What do I need to ad here?
if not exist "C:\Desktop\folderName\" mkdir C:\Desktop\folderName
What do I need to add to the Batch file?
EDIT:
This works
if not exist "C:\Desktop\%1\" mkdir C:\Desktop\%1
Batch Script
The following will create a directory only if that directory does not exist
if not exist "C:\Users\%USERNAME%\Desktop\%1" (
mkdir "C:\Users\%USERNAME%\Desktop\%1"
)
Assuming you save this to file C:/Documents/NameFolder.bat you just execute it with the same exact Java code
Process p = Runtime.getRuntime().exec("C:/Documents/NameFolder.bat folderName");
This will create a c:\Users\%USERNAME%\Desktop\folderName directory only if that directory doesn't already exist.
This is not best practice. Please read up on executing shell/batch scripts from Java
I am trying to compile and run this program by using eclipse. How do I do this?
I cant include the command line in the program. how do i use eclipse to run the program by using this command line??
I know theres another way of making the program by using Scanner but how do i run this one properly???
Cant post an image. Just joined.
INPUTTING FROM A FILE
Display a text file.
/*To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.
java ShowFile TEST.TXT */
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException exc) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException exc) {
System.out.println("Usage: ShowFile File");
return;
}
// read bytes until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Right click on your program, Hover over to Run As and Click Run Configurations
You will see a dialog box, now click on Arguments tab and specify the command line arguments.
I am not sure what you are asking, but to view the output of your program in the console:
You can do:
Window > Show View > Console
If you want to you want to compile from the command line you can use javac.
Right click on your program, Hover over to Run As and Click Run Configurations You will see a dialog box, now click on Arguments tab and specify the command line arguments.
On Program Arguments simply write file name OR file Address No need to write java ShowFile in your case it will be TEST.TXT .
Note : Make sure that TEST.TXT file is in your project folder
I have written some code for executing .bat file. which contains some
commands like setting java classpath,etc..And finally there is one command
which runs a Java class file.The HelloWorld class converts some xml file and generating a new xml file in some folder. When I double click .bat file, it executes fine,
but when I try to run I am not getting any output as I was getting through
double click the .bat file. How to make a batch execute and probably it would be nice
if I could see the results through Java console.
Following is MyJava code to execute the .bat file
public void run2() {
try {
String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
Process p = Runtime.getRuntime().exec(commands);
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
And below the some commands which has been set to .bat file
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java/classes
java -cp test.jar;test2.jar test.HelloWorld
Tried with "/C" commad as well. It does not execute. Actually it does not give effect of double click the .bat file. Is there any other way that I can try with?
I can see the contents inside the .bat file through Eclipse console. But it does not give the desired output. Desired output means when I double click .bat file, it executes well. But through java call, I can see the contents only .
When using cmd.exe use /C-Parameter to pass command:
String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
according to this, the Windows CMD needs the /c argument, to execute commands like this. try this:
String []commands = {"cmd.exe","/c","C:/MyWork/Java/classes/run.bat"} ;
Windows uses \ backslash for Windows and MS-DOS path delimiter. Forward slash / is accepted by Java in the java.io package and translated to be a path delimiter, but will not be directly acceptable to Windows or accepted by the cmd.exe shell.
You may also need to specify either the working directory for the batch file to be executed in, or possibly a full path to the cmd.exe command interpreter.
See: Runtime.exec (String[] cmdarray, String[] envp, File dir)
String[] commands = {"C:\\Windows\\System32\\cmd.exe", "/c",
"C:\\MyWork\\Java\\classes\\run.bat"};
File workDir = new File( "C:/MyWork");
Process process = Runtime.getRuntime().exec( commands, null, workDir);
To verify if the batch file is run at all, add a pause command to the batch file. That will keep the window open so you can verify if the batch file is launched at all, and debug this stage-by-stage.
You do not read the error output of your batch file, therefore, you'll never see any error messages printed from there or from CMD.EXE itself. In addition, the sub-program may stall and just wait for you to read the error stream.
Please see related discussions here: How to make a java program to print both out.println() and err.println() statements?
I want to open Notepad in my Java program. Suppose that I have one button if I click this button the notepad will appear.
I already have a file name and a directory.
How can I implement this case?
Try
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().edit(file);
} else {
// I don't know, up to you to handle this
}
Make sure the file exists. Thanks to Andreas_D who pointed this out.
(assuming you want notepad to open "myfile.txt" :)
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "myfile.txt");
pb.start();
Assuming you wish to launch the windows program notepad.exe, you are looking for the exec function. You probably want to call something like:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\path\\to\\notepad.exe C:\\path\\to\\file.txt");
For example, on my machine notepad is located at C:\Windows\notepad.exe:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\Windows\\notepad.exe C:\\test.txt");
This will open notepad with the file test.txt open for editing.
Note you can also specify a third parameter to exec which is the working directory to execute from - therefore, you could launch a text file that is stored relative to the working directory of your program.
Using SWT, you can launch any
If you want to emulate double-clicking on a text in windows, it's not possible only with a plain JRE. You can use a native library like SWT and use the following code to open a file:
org.eclipse.swt.program.Program.launch("c:\path\to\file.txt")
If you don't want to use a third-party lib, you should know and you know where notepad.exe is (or it's visible in PATH):
runtime.exec("notepad.exe c:\path\to\file.txt");
Apache common-exec is a good library for handling external process execution.
UPDATE: A more complete answer to your question can be found here
In IDE (Eclipse) it compains about "C:\path\to\notepad.exe C:\path\to\file.txt" .
So i have used the following which works for me keeping me and my IDE happy :o)
Hopefully this will help others out there.
String fpath;
fPath =System.getProperty("java.io.tmpdir")+"filename1" +getDateTime()+".txt";
//SA - Below launches the generated file, via explorer then delete the file "fPath"
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("explorer " + fPath);
Thread.sleep(500); //lets give the OS some time to open the file before deleting
boolean success = (new File(fPath)).delete();
if (!success) {
System.out.println("failed to delete file :"+fPath);
// Deletion failed
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String fileName = "C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\Student Project\\src\\studentproject\\resources\\RealWorld.chm";
String[] commands = {"cmd", "/c", fileName};
try {
Runtime.getRuntime().exec(commands);
//Runtime.getRuntime().exec("C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\SwingTest\\src\\Test\\RealWorld.chm");
} catch (Exception ex) {
ex.printStackTrace();
}
You could do this the best if you start notepad in command line with command: start notepad
String[] startNotePadWithoutAdminPermissions = new String[] {"CMD.EXE", "/C", "start" "notepad" };
Save array of string commands and give it like parametr in exec
Process runtimeProcess = Runtime.getRuntime().exec(startNotepadAdmin2);
runtimeProcess.waitFor();
I am trying run a batch file from my java codes, but unfortunately I could not
run it properly. Actually the batch file is running but only the first line of the batch file
is running, so please give solution to it, here are the codes and the batch file.
class bata
{
public static void main(String [] args)
{
try
{
Runtime.getRuntime().exec("start_james.bat");
}
catch(Exception e) {}
}
}
and the batch file is
cd\
c:
cd C:\Tomcat 5.5\webapps\mail_testing\james-2.3.2\bin
run.bat
start
What do you expect cd: to do? That doesn't look right to me...
If your batch file is only going to run another batch file, why not run that target batch file to start with? If you're worried about the initial working directory, use the overload which takes a File argument to say which directory to use. For example:
File dir = new File("C:\\Tomcat 5.5\\webapps\\mail_testing\\james-2.3.2\\bin");
Runtime.getRuntime().exec("start_james.bat", null, dir);
If all the other answers (with valid batch file) didn't work try executing cmd.exe directly like this:
File dir = new File("D:\\tools\\bin");
Runtime.getRuntime().exec("c:\\windows\\system32\\cmd.exe /c start_james.bat", null, dir);
You might also use the %SystemRoot% environment variable to get the absolute path to cmd.exe.
Isn't there something in java, whereby you can invoke the batch file directly with full path?
I mean, why do you need to change directories?
Also, what is the use of cd:? It is not a valid command in DOS, unless you are using *nix.
I think he wants to change to a directory and then run the batch file. Can you try this ?
cd /d C:\Tomcat 5.5\webapps\mail_testing\james-2.3.2\bin
run.bat
start
Was "cd:" supposed to be a label you can jump to using the GOTO command? However labels are declared using ":labelname". This should be the reason why your batch execution stops after the first line.
This works like a charm:
Runtime run = Runtime.getRuntime();
try
{
System.out.println("Start Running the batch file");
Process p = run.exec(new String[]{"cmd.exe","/c", "start", "C:/Users/sony/Documents/NetBeansProjects/CodeReview/src/codereview/install.bat",i,j,m,l});
System.out.println("Completed");
}
catch (Exception e)
{
}
here i,j,k,l are parameter passing to batch file