Question

Lets say that I have this code

moveDirectory.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
    try{
        Process send = Runtime.getRunetime().exec(new String[] {"cd /sdcard/music/", "cp pic1 /sdcard/pic1"});
        send.waitFor();
    } catch (Exception ex){
        String toast = null;
        Log.i(toast, "Couldn't copy file", ex);
        }
    }
});

If it fails to copy "pic1" how can I check it? so I can let the user know using a Toast? My only thought is to write code after that one to check if "pic1" is in the right path ("/sdcard/" in this case), but maybe there's an easier way.

Was it helpful?

Solution

you could read the command output. In cp command no output means no error, if there is output you could show it to the user to inform the error.

To read the command output you should add something like:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(send.getInputStream()));  

String line;  
ArrayList<String>  output = new ArrayList<String>(); 

while ((line = bufferedReader.readLine()) != null){ 
  output.add(line); 
} 

good luck.

OTHER TIPS

First it looks like your invocation of exec is not the one intended. Based on the docs if you pass it an String array, the first element of the array is the command and the rest the parameters. Here you have two commands instead.

You can write it just using one command very easily and using the single String invocation of exec:

  Process send = Runtime.getRuntime().exec("cp /sdcard/music/pic1 /sdcard/pic1");

Second, no exeception is thrown by waitFor in order to indicate that the command did not succeed. Based on documentation they only checked exception that will be thrown is to indicate that the current thread has been interrupted and in that case there is the possibility that the command has not even finished.

What you need to do is to check the exit status code of the process. This is the value returned by waitFor method. Is common practice that processes/programs return exist status 0 to indicate success and some other value to indicate an error. So the code should be instead:

  Process send = Runtime.getRunetime().exec("cp /sdcard/music/pic1 /sdcard/pic1");
  try {
    if (send.waitFor() != 0) {
        String toast = null;
        Log.i(toast, "Couldn't copy file", ex);
    }
  } catch (InterruptedException e) {
    // up to you how to recover this situation.
  } 

Third and foremost ... if what you want to do is to copy a file there is no need to call the system for that. You can use the java.io API to write you own file copying program... but better to reuse apache commons FileUtils helping class.

import org.apache.commons.io.FileUtils;
import java.io.File;

...
FileUtils.copyFile(new File("/sdcard/music/pic1"),new File("/sdcard/music"))
...

Have you tried send.exitValue() and then check if it is an error code like -1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top