Search code examples
javaandroidshellsu

How to check if a command succeeded?


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.


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.