Android:在 InstrumentationTestCase 中使用从 UiAutomation.executeShellCommand() 返回的 ParcelFileDescriptor

Android: Using the ParcelFileDescriptor returned from UiAutomation.executeShellCommand() in InstrumentationTestCase

我已经为我的 InstrumentationTestCase 子类编写了一个通用的 shellCommand 函数。对 executeShellCommand 的调用有效(命令已执行),但我对 returned ParcelFileDescriptor 做错了,因为它似乎 return 垃圾。这是我的通用 shellCommand 函数 -

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;
}

这里有一个片段显示我称它为 -

String output = shellCommand("ls -al /");
Log.d(TAG, String.format("root dir = {%s}", output)); 

我希望收到命令的输出字符串(在本例中,是顶级目录列表)。相反,我看到了以下日志 -

shellCommand: buf '[B@1391fd8d'

我对Java不是很好,我只是用它来编写一些自动化测试。我显然在 ParcelFileDescriptorBufferedInputStream 上做错了什么,有人可以解释一下吗?

toString() 方法实际上并不将字节数组的内容转换为字符串。它returns"a string representation of the object"。在这种情况下,'[B@1391fd8d' 表示 "the byte array whose hashcode is 1391fd8d" - 不是很有用吗?

您可以使用新的 String(byte[]) 构造函数将 byte[] 转换为 String。

然而,使用 BufferedReader.readLine() 直接从每一行输出中获取字符串可能更容易。