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

4

我为我的InstrumentationTestCase子类编写了一个通用的shellCommand函数。调用executeShellCommand函数可以正常工作(命令被执行),但是我在处理返回的ParcelFileDescriptor时出现了问题,因为它似乎返回了垃圾数据。下面是我的通用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方面出了些问题,请有人解释一下吗?
1个回答

2

toString()方法实际上并不会将字节数组的内容转换为字符串。它返回“对象的字符串表示形式”。在这种情况下,'[B@1391fd8d'表示“哈希码为1391fd8d的字节数组”,并没有什么用。

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

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


谢谢 Allen!问题已解决。我之前使用了 int.toString() 并且认为 byte[].toString() 也会有同样的行为。 - fourjays

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接