Java Android:使用InstrumentationTestCase中UiAutomation.executeShellCommand()返回的ParcelFileDescriptor
我已经为我的Java Android:使用InstrumentationTestCase中UiAutomation.executeShellCommand()返回的ParcelFileDescriptor,java,android,android-5.0-lollipop,android-uiautomator,Java,Android,Android 5.0 Lollipop,Android Uiautomator,我已经为我的InstrumentationTestCase子类编写了一个通用的shellCommand函数。调用executeShellCommand有效(该命令已执行),但我对返回的ParcelFileDescriptor做了一些错误,因为它似乎返回垃圾。这是我的通用shellCommand函数- public String shellCommand(String str) { UiAutomation uia = getInstrumentation().getUiAutomatio
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));
我希望收到命令的输出字符串(在本例中,是顶级目录列表)。相反,我看到了下面的日志-
shell命令:buf'[B@1391fd8d"
我对Java不是很在行,我只是用它来编写一些自动化测试。我显然对ParcelFileDescriptor
或BufferedInputStream
做了一些错误,有人能解释一下吗?该方法实际上并没有将字节数组的内容转换为字符串。它返回“对象的字符串表示形式”。在本例中,'[B@1391fd8d'表示“哈希代码为1391fd8d的字节数组”-不是很有用吗
可以使用新构造函数将字节[]转换为字符串
但是,直接从每一行输出中获取字符串可能更容易使用。谢谢Allen!这已经解决了。我以前使用过
int.toString()
,只是假设byte[].toString()
也会以同样的方式运行。