Search This Blog

Showing posts with label parameters. Show all posts
Showing posts with label parameters. Show all posts

How to Launch a Application or Executable Using Java Code with Command Line Arguments

In this post, we shall see how to launch an application with its command line arguments using Java code. Most applications take path of a file as command-line argument to open it. If we give path of an image file to mspaint application as command-line argument, the image will be opened in paint. The following java program launches mspaint with a command-line argument which is a path to an image.

 try
 {
 Runtime.getRuntime().exec("C:\\Windows\\System32\\mspaint.exe \"C:\\Users\\Shareef\\Desktop\\flower.jpg\"");
 } catch (IOException ex) {}

Arguments are separated by spaces. If a command-line argument contains space within it (such as a space in a path), it is recommended to enclose it within brackets.

How to Easily Copy a File to Another File or Location in Java

The Files class in java has many useful static methods to copy and move files, create temporary files or folders etc. To copy a file from one location to another in Java, there is a static method copy in Files class. The Files class is in java.nio.file package. The method Files.copy() takes three arguments (parameters) : Path of source file (as object of Path class), Path of destination file ( as object of Path class ) and an option parameter. The option parameter can be one of the following:

StandardCopyOption.REPLACE_EXISTING
If the target file exists, then the target file is replaced.

StandardCopyOption.COPY_ATTRIBUTES
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes
that are copied is platform and file system dependent and therefore unspecified.

StandardCopyOption.NOFOLLOW_LINKS
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.

You have to import java.nio.file.StandardCopyOption to use option parameters.

try{
File sourcefile=new File("audio.mp3");
File destination=new File(System.getProperty("java.io.tmpdir")+"\\temp.mp3");
Files.copy(sourcefile.toPath(),destination.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException ex) {
ex.printStackTrace();
}

For the copy method, there are two other overloaded method definitions. In one, instead of source file's path, inputstream is the first parameter and the rest are same. For the other overloaded definition, an outputstream object is the second parameter instead of destination path object and the rest are same.

Similarly, to move a file from one location to another, there is a method move() in Files class. The parameters of this method is also same as those of copy method.