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
Related
I am trying to execute a bat file using java. This bat file contains code that should create a .csv file in the same directory. The .csv file is successfully created when I execute the .bat file by running it on my Windows machine, however when I try to execute it in java using Runtime.getRuntime().exec(), the file does not get created.
String[] command = {"cmd.exe", "/C", "C:/Users/MidiCsv/ex.bat"};
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
try {
p.waitFor();
System.out.println("ready");
} catch (InterruptedException e) {
e.printStackTrace();
}
content = Files.readString(Paths.get("C:/Users/MidiCsv/" + midiName + ".csv"), StandardCharsets.US_ASCII);
The value returned by the p.waitFor() method is 2, I assume this means there was an error here since the normal return value is 0. What error could this indicate?
If the working directory is required to be same as your batch file, use this variant of exec method instead:
public Process exec(String[] cmdarray,
String[] envp,
File dir)
throws IOException
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String[],%20java.lang.String[],%20java.io.File)
Make dir the directory containing your batch file.
I figured out the error from taking the helpful advice here. I used the exec() variant Febtober mentioned, also previously I was putting the absolute path of the .batch file as the dir paramter, whereas I should have put the directory of the .batch file instead.
I know how to create directories inside any directory using Java. But I am unable to find a solution to add directories inside a directory which requires sudo permission to create a directory inside it.
For eg, I want to create new directories named abc/abc inside /var/log/.
I am uisng following code :
public class CreateDirectories{
public static void main(String args[]){
File file = new File("/var/log/java-jdbc/java-jdbc");
if(!file.exists()){
if (file.mkdirs()) {
System.out.println("Directory is created!");
}
else{
System.out.println("Failed to create directory!");
}
}
}
}
This code always runs giving output: Failed to create directory!
I am writing a java application, in which I am automatically importing external csv files in background to do the computation. But the problem is that I am using "absolute" file path in my java program, the generated jar file will not work in another computer. Is there anyway in java to use a kind of "working directory path" so that I can still run the jar file in another computer as long as I put the csv files I'd like to import in the same folder with the jar file?
Thanks!
You can read a file using its name like
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
String line;
while ((line=br.readLine())!=null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Here text.txt should be in the same working directory where the jar was executed.
You can also read the directory name from the command line, using the command line arguments like
public static void main(String[] args) {
//check if there were any command line arguments
if (args.length > 0) {
// args[0] is the first command line argument unlike C where args[0] would give u the executable's name
} else {
System.err.println("Usage: java -jar <jar_name> [directory_names..]");
}
}
You can also have a configuration file such as a properties file to read the directory names.
new File(".") give you the relative path
you can write relative path like that :
File file = new File(".\\CSVs\\myfile.csv");
System.getProperty("user.dir") will return you the working directory.
System.getProperty("user.dir")+"\\myfile.txt"
More informations here :system properties, oracle docs
I want to create an java program to compress an css file using YUI
I am new learner in java.
My Code is:
import java.io.BufferedInputStream;
import java.io.IOException;
public class Run extends Object
{
public static void main(String args[]) throws IOException, InterruptedException
{
System.out.println("Calling jar");
Process p = Runtime.getRuntime().exec("java -Xmx32m -jar yui.jar in.css");
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
synchronized(p)
{
p.waitFor();
}
System.out.println(p.exitValue());
int b = 0;
while((b = bis.read()) > 0)
{
System.out.print((char)b);
}
System.out.println("Called jar");
}
}
I took reference from here.
the command:
java -Xmx32m -jar yui.jar in.css
works fine in cmd but I get no output when I run above program
the output I get for above is:
Calling jar
1
Called jar
Please tell Me what I am doing wrong or what is the right way of doing this.
You are getting the "1" because there is nothing to read in the stream.
I'm guessing that you're trying to run the file from Eclipse or some other IDE. If so, you need to place your yui.jar and in.css files to same directory relative to where your Run class is.
If you're using default run configurations, you'll just want to put the files into the root directory of your eclipse project. For example, this works for me:
Test
src
com
test
Run.java
yui.jar
in.css
A better way to handle your situation is to use absolute or relative paths instead of just specifiying yui.jar or in.css. Create two variables for the two relative paths and then create the command string.
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