我为我的shellCommand子类编写了一个通用的InstrumentationTestCase函数。对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,我只是用它来编写一些自动化测试。很明显,我对ParcelFileDescriptor或BufferedInputStream做错了什么,谁能解释一下吗?
发布于 2015-06-14 23:01:44
toString()方法实际上并不将字节数组的内容转换为字符串。它返回“对象的字符串表示”。在本例中,‘B@1391fd8d’意为“哈希码为1391fd8d的字节数组”--不是很有用吗?
您可以使用新的[ String ( byte[] )](http://developer.android.com/reference/java/lang/String.html#String(byte[]%29)构造函数将一个字符串转换为字符串。
但是,使用BufferedReader.readLine()直接从每一行输出中获取字符串可能更容易。
https://stackoverflow.com/questions/30800862
复制相似问题