Create a file using Runtime.exec using echo in linux?

Asked
Active3 hr before
Viewed126 times

7 Answers

createusing
90%

I'm having trouble using Runtime.exec in Java, it seems some commands work while others do not. For example if I run ,Thanks for contributing an answer to Stack Overflow!,edit because redirection is a little different using Runtime,Connect and share knowledge within a single location that is structured and easy to search.

Here's a quick example that does work with redirection.

public class RunTest {
   public static void main(String[] args) throws Exception {
      String[] commands = {
         "bash",
         "-c",
         "echo hello > hello.txt"
      };
      Runtime.getRuntime().exec(commands);
   }
}
88%

To create the file with the echo command, execute the command as follows:,using redirect '>' symbol,To create a file with the printf command, execute the command as follows:,To create a file with redirect (>) operator, execute the command as follows:

[sudo] password
for javatpoint:
   Reading package lists...Done
Building dependency tree
Reading state information...Done
The following additional packages will be installed:
   vim - runtime
Suggested packages:
   ctags vim - doc vim - scripts
The following NEW packages will be installed:
   vim vim - runtime
0 upgraded, 2 newly installed, 0 to remove and 64 not upgraded.
Need to get 6, 878 kB of archives.
After this operation, 33.4 MB of additional disk space will be used.
Do you want to
continue ?[Y / n] y
Get: 1 http: //in.archive.ubuntu.com/ubuntu eoan/main amd64 vim-runtime all 2:8.1.0875-5ubuntu2 [5,669 kB]
   Get: 2 http: //in.archive.ubuntu.com/ubuntu eoan/main amd64 vim amd64 2:8.1.0875-5ubuntu2 [1,209 kB]
   Fetched 6, 878 kB in 3 s(2, 256 kB / s)
Selecting previously unselected package vim - runtime.
   (Reading database...216385 files and directories currently installed.)
Preparing to unpack.../vim-runtime_2%3a8.1.0875-5ubuntu2_all.deb ...
Adding 'diversion of /usr/share/vim/vim81/doc/help.txt to /usr/share/vim/vim81/doc/
help.txt.vim - tiny by vim - runtime '
Adding 'diversion of /usr/share/vim/vim81/doc/tags to /usr/share/vim/vim81/doc/tags
   .vim - tiny by vim - runtime '
Unpacking vim - runtime(2: 8.1 .0875 - 5 ubuntu2)...
   Selecting previously unselected package vim.
Preparing to unpack.../vim_2%3a8.1.0875-5ubuntu2_amd64.deb ...
Unpacking vim(2: 8.1 .0875 - 5 ubuntu2)...
   Setting up vim - runtime(2: 8.1 .0875 - 5 ubuntu2)...
   Setting up vim(2: 8.1 .0875 - 5 ubuntu2)...
   update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / vim(vim) in auto
mode
update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / vimdiff(vimdiff) in auto mode
update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / rvim(rvim) in au
to mode
update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / rview(rview) in
   auto mode
update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / vi(vi) in auto m
ode
update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / view(view) in au
to mode
update - alternatives: using / usr / bin / vim.basic to provide / usr / bin / ex(ex) in auto m
ode
Processing triggers
for man - db(2.8 .7 - 3)...
72%

The exec() method offers a few overloaded variations:,public Process exec(String cmdArray[], String[] envp) - Executes a command with the specified environment variables.,public Process exec(String command) - Executes the command contained in command in a separate process.,public Process exec(String cmdArray[]) - Executes a command in the form of an array of Strings.

Let's start off with the simplest approach out of these three:

Process process = Runtime.getRuntime().exec("ping www.stackabuse.com");
load more v
65%

In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command :,Java doc – ProcessBuilder,More ProcessBuilder examples, ProcessBuilder p = new ProcessBuilder(cmd);

package com.mkyong.shell;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExecuteShellComand {

	private static final String IPADDRESS_PATTERN = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])" 
		+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])" 
		+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])" 
		+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])";

	private static Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
	private static Matcher matcher;

	public static void main(String[] args) {

		ExecuteShellComand obj = new ExecuteShellComand();

		String domainName = "google.com";
		String command = "host -t a " + domainName;
		
		String output = obj.executeCommand(command);

		//System.out.println(output);
		
		List<string> list = obj.getIpAddress(output);

		if (list.size() &gt; 0) {
			System.out.printf("%s has address : %n", domainName);
			for (String ip : list) {
				System.out.println(ip);
			}
		} else {
			System.out.printf("%s has NO address. %n", domainName);
		}

	}

	private String executeCommand(String command) {

		StringBuffer output = new StringBuffer();

		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			BufferedReader reader = 
                           new BufferedReader(new InputStreamReader(p.getInputStream()));

			String line = "";			
			while ((line = reader.readLine())!= null) {
				output.append(line + "\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return output.toString();

	}

	public List<string> getIpAddress(String msg) {

		List<string> ipList = new ArrayList<string>();

		if (msg == null || msg.equals(""))
			return ipList;

		matcher = pattern.matcher(msg);
		while (matcher.find()) {
			ipList.add(matcher.group(0));
		}

		return ipList;
	}
}
</string></string></string></string>

Output

google.com has address:
   74.125 .135.x
74.125 .135.x
74.125 .135.x
74.125 .135.x
74.125 .135.x
74.125 .135.x

You can also use

ProcessBuilder pb = new ProcessBuilder(computeCommandLine());
pb.directory(workingDirectory);

Map<String, String> env = pb.environment();
   env.put("VAR1", "myValue");
   env.remove("OTHERVAR");
   env.put("VAR2", env.get("VAR1") + "suffix");

   Process p = pb.start();
   ...
 #
 # A fatal error has been detected by the Java Runtime Environment:
    #
 # EXCEPTION_ACCESS_VIOLATION(0xc0000005) at pc = 0x10038859, pid = 4248, tid = 204
 #
 # JRE version: 6.0_18 - b07
 # Java VM: Java HotSpot(TM) Client VM(16.0 - b13 mixed mode, sharing windows - x86)
 # Problematic frame:
    # C[mpe.dll + 0x38859]
 #
 # An error report file with more information is saved as:
    # C: \Users\ workspace\ EJBWS\ DLLSTest\ hs_err_pid4248.log
 #
 # If you would like to submit a bug report, please visit:
    # http: //java.sun.com/webapps/bugreport/crash.jsp
    # The crash happened outside the Java Virtual Machine in native code.
 # See problematic frame
 for where to report the bug.
 #
load more v
75%

Tcsh. If you are using the tcsh shell, append the following line to your /u/username/.tcshrc file: setenv PATH ~/j2sdk1.6.0.18/bin:$PATH Then close your shell and open up a new one. , You will type commands in an application known as the shell. Since you're using Linux, we assume you're somewhat familiar with it. , To configure Java, you will need to know which shell you are running. In case you don't know, type the following command: [wayne] ~> echo $SHELL Your shell will likely be bash, tcsh, sh, or ksh. ,Bash. If you are using the bash shell, append the following line to your /u/username/.bashrc file. If it doesn't exist, create a new one. Here, j2sdk1.5.16/bin is the location of the javac and java executables. export PATH=$PATH:~/j2sdk1.6.0.18/bin Then close your shell and open up a new one. If it does not work, in addition, try repeating the same instructions with the file /u/username/.bash_profile.

[wayne] ~ > echo $SHELL
load more v
40%

This is also similar to cat command, but it is very flexible comparatively. The following command is usually used for printing text on the terminal, but we can also use it to write to a file or make an empty file. The echo command is used along with the double redirect symbols (single > will also work) followed by the filename. ,If you want to create several text files at once, then you can add the redirect symbol after the previous filename and chain the command repeatedly to create multiple empty files.,It is also quite easy to understand the command to create a text file in the terminal with the minimum effort. This works really very well for creating a single text file quickly, but for creating several text files at once it becomes a bit tedious. The command is simply using the standard redirect symbol (>) spacebar followed by the file name. ,Using the redirect symbol for creating files.

This is the most standard command to quickly create an empty text file. The command is quite simple to type and makes it quite easier to create several text files at once. The commands are as follows:

touch filename.txt
load more v
22%

private static void execCommand() {
   String[] command = {
      "echo",
      "Hello",
      "world."
   };

   new Thread(() - > {
      try {
         ProcessBuilder builder = new ProcessBuilder(command);
         builder.redirectErrorStream(true);
         final Process proc = builder.start();
         BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
         String s = null;
         while ((s = in .readLine()) != null) {
            System.out.println(s);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }).start();
}
load more v

Other "create-using" queries related to "Create a file using Runtime.exec using echo in linux?"