I want to create a folder that starts with . character. I tried File(path).mkdir() but does not work. I cannot create from "right click->new folder". Windows blocks creating folders starting with dot character. From command prompt I can easily create via mkdir [folder_name]. Do I have any mistakes here. If not how can I execute this command in java or any other suggestion will be helpful?
Note: Process p = Runtime.getRuntime().exec("mkdir .test"); //Does not work
Note2: My code will be platform dependent.
new File("C:\\Temp\\.folder").mkdir();
Works for me. Note that mkdir() returns a boolean which indicates success or failure. It can fail if you have no permission to create the folder, for example.
(Note: When you ask a question, explain what "does not work" means.)
Platform independant OS functions are not so simple in java but you could wrap it around an ant mkdir task that would be platform independant. The usage is slightly roundabout but is/could be quite powerful
Related
I am a high school student working on a project that will convert the video from a YouTube link into an MP3 and download it. However, the way that the video form YouTube is downloaded and converted is through the Mac OS terminal by using YouTube-dl.
This is what I put into the terminal:
youtube-dl -f bestvideo+bestaudio \"ytsearch:{https://www.youtube.com/watch?v=5X-Mrc2l1d0}\"
This works in terminal, but when I try to use:
Runtime.getRuntime().exec("cd /Users/poppa/Desktop/IA Vids");
and there's an error saying "No such file or directory"
Another Problem that I am having is running the code that is inputted into the Terminal from Java. I'm using IntelliJ IDEA if that helps. Thank You!
You have a space in the directory path. Try putting double quotes around like this:
Runtime.getRuntime().exec("cd \"/Users/zeidakel/Desktop/IA Vids\"");
Also note that executing cd command from JVM may have no effect on current user dir when (for example) creating files with new File("path")
If cd means change directory (and isn't the name of an executable), then it almost certainly won't take effect, even if it is executed correctly. The process spawned by exec() will have a working directory, and it can be changed -- but that change will only affect the spawned process.
In addition, having spaces in arguments to exec() is inherently problematic. exec() is not a shell, and you won't be able to protect the string from being split at the spaces by using shell mechanisms like quotes. Instead, you need to split the command into arguments yourself, knowing where the splits should be, and then use the form of exec() that takes a String[] as input. That is, split the arguments into an array of strings yourself, rather than relying on exec() to do it for you (wrongly).
Runtime.exec() is fraught with difficulties, and needs very careful handling. I've written extensively about this subject here:
http://kevinboone.me/exec.html
I have written a program in Clojure and I'd like to execute it on the command-line without specifically invoking java on the command-line (such as java -jar). I want a single executable file, such as myprogram, that accepts any arguments and runs my program. Here are a couple things that might make this easier:
It's OK to assume Java is installed and that java is in the path.
Although a solution that works on Windows would be a great plus, you can assume that this is all being done on a UNIX-like operating system such as Mac OS X or Ubuntu.
It's OK to invoke Java in a script of some kind.
It's OK to use some other language, such as Ruby, Python or Perl, which the user may or may not have installed. All-bash would be cool because I can assume people have that.
It's OK if I have to use some kind of tool to build a binary that will execute, but I am not looking for a .app or .exe file that expects to operate with a GUI interface (so for example, Oracle's appbundler is not what I'm looking for here).
I have gotten pretty far down this path with one approach, but I have to wonder if there's a better way.
FOR REFERENCE ONLY: What I've Tried Already
I'll describe my approach below, but any answers don't need to follow this approach at all.
What I have done is create a lein plugin called makescript that generates an uberjar, base64 encodes it, and places it inside a Ruby script in a so-called heredoc variable, like this:
# ...ruby script...
BASE64_JAR = <<-JAR_BOUNDARY
# [...base64 encoded file here...]
JAR_BOUNDARY
You should then be able to run the ruby script. It will take the BASE64_JAR variable, unencode it, place it in a temporary file, and execute it by invoking java -jar <filename>.
The problem I'm having with this approach is that Ruby's base64 library and Clojure's clojure.data.codec.base64 libraries seem to be producing different strings to represent the jar, and a string encoded by Clojure does not decode to the original file if I use Ruby. This may have something to do with the encoding of the strings themselves (UTF-8-related? maybe) between the two languages. Here are repl/irb sessions that illustrate the disconnect:
repl=> (def jar-contents (slurp "../target/myproj-0.1.0-SNAPSHOT-002-standalone.jar"))
repl=> (count jar-contents) ;; => 9433328
repl=> (def a-str (String. (clojure.data.codec.base64/encode (.getBytes jar-contents)) "UTF-8"))
repl=> (count a-str) ;; => 23265576
irb> f = File.open("target/pwgen-0.1.0-SNAPSHOT-002-standalone.jar", "r").read()
irb> p f.length # => 9657639
irb> b = Base64.encode64(f)
irb> p b.length # => 13564973
Note the raw sizes are close but not the same, but the encoded versions are much different.
Although this is puzzling and I'd like to know why this happens, I think I can bypass the problem by having makescript just generate the uberjar and pass the path to another Ruby script, which then will base64 encode (and later decode, also using Ruby) the standalone JAR. The question still stands: is there a better, simpler way? Am I missing something obvious, or is this really as hard as it seems?
If you really want to do it, you can uuencode the jar file (or any other binary file) in a bash executable, see this for an example: Embed a Executable Binary in a shell script
It sounds like you're just trying to bootstrap your app from a script using cleaner syntax. This might be most easily done like so:
create a new bash script called myprogram:
#!/usr/bin/bash
# pass whatever command line args you have down through the script
java -jar myjar.jar
give it execute permissions
chmod +x myprogram
run it
./myprogram (with whatever params)
If you want to get rid of the ./ you'll need to move things around so the script gets picked up by your PATH.
Keep in mind that you're not creating a platform specific binary executable. Doing so would pretty much defeat the purpose of using the jvm in the first place. You'd just be invoking it through an extra layer of indirection.
Now that GraalVM has matured a little bit, you may want to consider compiling your application to a binary executable.
There's a good tutorial of how to accomplish that here.
What about running clojure as an interpretive script. Create a new file called mytest:
#!/usr/bin/clojure
(print "hello world")
and then
chmod +x mytest
and then simply run it
./mytest
There are plenty of drawbacks to this. It's really slow to start. This simple 1 liner took over 2 seconds to run! You're only going to get a single file. Probably this is useful only for the most simple things. But this could be useful if you're just trying to do something quickly which isn't production or test something.
I have a Main.java file and I want to run the program passing it test.txt
I know in command line I can write javac Main.java
After compiling I can write java Main test.txt and this will accomplish running the file and passing test.txt
If I wanted instead to be able to just write main test.txt and have that trigger my Main.class file to run is that possible and if so how?
(Edit: Based on your comment, let me expand to add a couple more situations)
If your goal is to have someone else run your program who does not have Java installed, and you do not wish to have them install a Java runtime environment before running your app, what you need is a program that converts the .class or .jar files into a native executable for the platform you are using. How to do this has been covered in other questions, eg: Compiling a java program into an executable . Essentially, you use a program like JCG (GNU Compiler for Java) or Excelsior JET (a commercial product) to expand the byte code into full native code with a mini-JRE built in.
If your goal is to save typing, there are a number of strategies. Others have suggested alias commands, which work well on linux.
A slightly more portable option that you could ship with your program would be a shell script. Granted, shell scripts only run on linux or other OS's with shell script interpreters installed.
Here is an example shell script. You paste this into a text editor and save it as main with no extensio. The $1 passes the parameter argument fyi.
#!/bin/sh
java Main $1
presuming you name your shell script just "main" with no extension, you could call main test.txt to execute your program now.
If you are on Windows, you might want to create a windows shortcut, and point the shortcut to "java Main test.text", using the full paths if necessary (if the paths are not already set). Of course, this does not make the parameter easy to change every time you run it, you would have to edit the shortcut.
add an alias
e.g. under a mac edit your .bash_profile with the following line
alias main='java main'
don't forget to open a new console to see your alias working
Depends on your operating system. On Linux with the bash shell, for instance, you can set up an alias to expand your main into java -cp myjar.jar main.
Linux can also be configured to 'understand' Java class flies as a binary format directly see here (linux kernel documentation).
If you're on windows, you'll have to wait for answer from someone with more knowledge about that than I.
Good luck!
I am trying to run a perl command with Java runtime exec in linux/ubuntu/gnome. The command generates an pdf file, but it saves it in my home folder. Is there any way that the exec method can set an output path for the commands executed? Thanks in advance.
The exec method just runs the command on the operating system, so you'll want to change the command you're running with exec more than anything in "Java" per se.
There are a few possibilities:
Change the working directory of your java program. The .pdf is being saved in your working directory because this is where the program is being run.
Unfortunately it's not simple to change this value after the program has been launched. It is, however, trivial to change before the program starts; just change the working directory before starting the program.
Move the file to it's desired location after it's been created in your home directory.
Change the command so that it includes the target location. Your perl script may have an option that will enable you to save it's output to a certain location (usually -o or --output). Using this your program would change from:
Runtime.exec("perl someprogram");
to something like:
Runtime.exec("perl someprogram -o /path/to/some.file")
You might be able to use "output redirection", if there is no option to do this.
Try something like what's below as your argument:
Runtime.exec("perl someprogram > /path/to/some.file")
Unfortunately, without knowing more details of your situation I can't provide more concrete advice.
While each approach has benefits and drawbacks, it's probably best to just implement the one that you understand best; if you can't get one to work, try another.
A good, free online resource for learning is Introduction to Linux: A Hands On Guide.
Section 2.2 has details on cd which you can use for 1..
Section 3.3, section 3 teaches about the mv command, which will be useful in 2..
Section 5.1 is about I/O redirection. Knowing about "output redirection" and the > operator, are important for 4..
For 3., you'll have to consult the documentation of the perl program you're using.
You could modify the Perl script to accept an absolute path for the output.
You can trying setting the working directory using exec(java.lang.String[], java.lang.String[], java.io.File) where File is the directory the command is executed from.
If all else fails, you'll can always copy the generated file from the Home directory to your final location.
I want to use system commands like mkdir and rmdir while running a java program.
How can I do that?
Why do you want to use the command line? FYI, there are built-in platform-independent File classes.
http://www.exampledepot.com/egs/java.io/deletefile.html
http://www.roseindia.net/java/beginners/java-create-directory.shtml
Make directory:
new File("dir path").mkdir();
Remove directory:
new File("dir path").delete();
'new File' here is a bit of a misnomer, it isn't actually creating the directory or a file. It's creating a Java resource hook which you can use to query or operate upon an existing filesystem resource, or create a new one at your request. Otherwise, use Runtime.getRuntime().exec("command line here") for using command line operations (not advised!!).
Edit: sorted out the problem the question poster was having:
String envp[] = new String[1];
envp[0] = "PATH=" + System.getProperty("java.library.path");
Runtime.getRuntime().exec("command line here", envp);
Note the insertion of envp into the exec(..) method call, which is basically the PATH variable from the environment.
As the other mentioned, you shouldn't do this for simple file management. But to have it mentioned: The Java API has a class called Runtime, that allows system calls... for example:
Runtime.getRuntime().exec("some_command");
The best is not to, but rather find the pure Java API function that does it. It is cleaner, easier to understand and much less error prone. It is also the only way to do Java that is write once run everywhere. Once you are calling shell commands, you are tied to that shell.
In your case you are looking for the java.io.File class, and specifically the mkdir and delete methods.
For reference of people stumbling onto this question and wondering why Runtime.getRuntime().exec("mkdir foo") doesn't work even when incorporating the environment as per Chris Dennett's answer, the most probable reason is that you don't have a program called "mkdir" on your system. While most Unix-like systems have a program of this name, it isn't absolutely necessary for them to have one, and Windows doesn't have one, because in both cases the shell interprets this command itself, rather than passing it to an external program.
To make it work, try ...exec ("cmd /c mkdir foo") for NT-family Windows (or "command /c mkdir foo" for Windows 95 family), or exec ("sh -c \"mkdir foo\"") for Unix.
The fact that there isn't a platform-independent way to do this is yet another reason to prefer the Java APIs for performing the task.
Hi Agree to the fact of not been platform independent but just for testing an app I had to use it.
The solution in my case for the
Runtime.getRuntime().exec("my_command_name") ;
for not working was i had to give the full path to where the batch/sh/executable file was
ie:
Runtime.getRuntime().exec("/d/temp/bin/mybatfile");