首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android:在ParcelFileDescriptor中使用从UiAutomation.executeShellCommand()返回的InstrumentationTestCase

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

Stack Overflow用户
提问于 2015-06-12 10:30:42
回答 1查看 2K关注 0票数 2

我为我的shellCommand子类编写了一个通用的InstrumentationTestCase函数。对executeShellCommand的调用工作正常(命令被执行),但我对返回的ParcelFileDescriptor做了一些错误,因为它似乎返回垃圾。这是我的通用shellCommand函数-

代码语言:javascript
复制
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;
}

这里有段片段显示我叫它-

代码语言:javascript
复制
String output = shellCommand("ls -al /");
Log.d(TAG, String.format("root dir = {%s}", output)); 

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

shellCommand: buf '[B@1391fd8d‘

我不太擅长Java,我只是用它来编写一些自动化测试。很明显,我对ParcelFileDescriptorBufferedInputStream做错了什么,谁能解释一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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()直接从每一行输出中获取字符串可能更容易。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30800862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档