I've written a generic shellCommand
function for my InstrumentationTestCase
subclass. The call to executeShellCommand
works (the command is executed), but I'm doing something wrong with the returned ParcelFileDescriptor
, because it seems to return rubbish. Here's my generic shellCommand
function -
public String shellCommand(String str)
{
UiAutomation uia = getInstrumentation().getUiAutomation();
ParcelFileDescriptor pfd;
FileDescriptor fd;
InputStream is;
byte[] buf = new byte[1024];
String outputString = null;
try
{
pfd = uia.executeShellCommand(str);
fd = pfd.getFileDescriptor();
is = new BufferedInputStream(new FileInputStream(fd));
is.read(buf, 0, buf.length);
outputString = buf.toString();
Log.d(TAG, String.format("shellCommand: buf '%s'",outputString));
is.close();
}
catch(IOException ioe)
{
Log.d(TAG, "shellCommand: failed to close fd");
}
return outputString;
}
And here's a snippet showing me calling it -
String output = shellCommand("ls -al /");
Log.d(TAG, String.format("root dir = {%s}", output));
I was hoping to receive the command's output string (in this example, a list of top-level directories). Instead I see the following log -
shellCommand: buf '[B@1391fd8d'
I'm not great with Java, I just use it to write some automated tests. I'm obviously doing something wrong with the ParcelFileDescriptor
or BufferedInputStream
, can someone please explain what?
The toString() method doesn't actually convert the contents of a byte array to a String. It returns "a string representation of the object". In this case, '[B@1391fd8d' means "the byte array whose hashcode is 1391fd8d" - not very useful is it?
You can convert a byte[] to a String by using the new String(byte[]) constructor.
However it's probably easier to use BufferedReader.readLine() to get a String directly from each line of output.