Linux copies files from a Java program

I wrote a little java code with getRuntime () API to copy files from one directory to another, it doesnโ€™t work, I canโ€™t understand why? When I run the command from the shell, it works fine, can anyone, please let me know the error I'm making.

private static void copyFilesLinux(String strSource, String strDestination) { String s; Process p; try { // cp -R "/tmp/S1/"* "/tmp/D1/" p = Runtime.getRuntime().exec( "cp -R '" + strSource + "/'* '" + strDestination + "/'"); System.out.println("cp -R \"" + strSource + "/\"* \"" + strDestination + "/\""); System.out.println("cp -R '" + strSource + "/'* '" + strDestination + "/'"); System.out.println(p.toString()); BufferedReader br = new BufferedReader(new InputStreamReader( p.getInputStream())); while ((s = br.readLine()) != null) System.out.println("line: " + s); p.waitFor(); System.out.println("exit: " + p.exitValue()); p.destroy(); } catch (InterruptedException iex) { iex.printStackTrace(); } catch (IOException iox) { iox.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } 

Output:

 cp -R "/tmp/S1/"* "/tmp/D1/" cp -R '/tmp/S1/'* '/tmp/D1/' java.lang.UNIXProcess@525483cd exit: 1 
+4
source share
4 answers

It works with the code below,

  String[] b = new String[] {"bash", "-c", "cp -R \"" + strSource + "/\"* \"" + strDestination + "/\""}; p = Runtime.getRuntime().exec(b); 

I searched for it and found a link

http://www.coderanch.com/t/423573/java/java/Passing-wilcard-Runtime-exec-command

+1
source

When you use any change to Runtime.exec() , the binary is called directly, not through the shell. This means that wildcards are not supported because the shell does not extend them.

I would suggest using Java code to copy your files - it would be much more portable and secure. If this is forbidden, you can use the shell binary to execute your command using the -c option.

+2
source

You can do this using the standard java api if you really don't need to execute system commands.

http://docs.oracle.com/javase/tutorial/essential/io/copy.html

+1
source

It worked for me with the following code.

  public static void main(String []args) throws Exception{ String s; Process p; try { String b[] = new String[4]; b[0] = "cp"; b[1] = "-R"; b[2] = "HelloWorld.java"; b[3] = "abc.java"; p = Runtime.getRuntime().exec(b); BufferedReader br = new BufferedReader( new InputStreamReader(p.getInputStream())); while ((s = br.readLine()) != null) System.out.println("line: " + s); p.waitFor(); System.out.println ("exit: " + p.exitValue()); p.destroy(); } catch (Exception e) {} } } 

Create String[] commands and pass commands to them.

+1
source

All Articles