如何使用java打印android中进程返回的数据



我正试图从我的系统应用程序中读取与系统应用程序关联的xml文件。我在java中使用以下代码:

Process p = Runtime.getRuntime().exec("cat /data/data/app_pkg_name/shared_prefs/file.xml");

现在我知道我可以做了

 p.getInputStream() 

以获得与该进程相关联的输入流。如何在logcat中获得屏幕上xml的实际内容,并使用system.out.println()打印?

当我在adb shell的命令提示符上执行相同的命令(第一个)时,我会在控制台上打印xml文件的内容。如何在应用程序中做到这一点?

仅供参考,我的设备是,并且我已在清单中使用了必要的权限。

  /* You can use the below code to print the output using system.out.println() */

StringBuilder stringBuilder = new StringBuilder();
        try {
            String contents = "" ;
            Process p = Runtime.getRuntime().exec("cat /data/data/com.admarvel.testerofflineappv242/shared_prefs/myPrefs.xml");
            InputStream inputStream =  p.getInputStream();`enter code here`
            BufferedReader in = new BufferedReader(
                    new InputStreamReader( inputStream ) );
                while ( ( contents = in.readLine() ) != null )
                {
                    stringBuilder.append(contents);
                }
                in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("text" + stringBuilder);

使用下面的方法从InputStream中以String格式获取数据,并打印返回的String。。。

private String getDataFromStream(InputStream inputStream) {
    try {
        final StringBuffer buffer = new StringBuffer();
        byte[] bs = new byte[1024];
        int read = 0;
        while ((read = inputStream.read(bs)) != -1) {
            String string = new String(bs, 0, read);
            buffer.append(string);
        }
        inputStream.close();
        return buffer.toString();
    } catch (Exception exception) {
    }
    return ""; // we got exception or no data in Stream
}

有很多方法可以做到这一点。一种是将TextView添加到布局中,然后将其内容设置为流中的内容,例如

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent" 
          android:layout_height="fill_parent"
          android:orientation="vertical" >
<TextView android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="" />

然后在您的活动中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity_layout);
    TextView text = (TextView) findViewById(R.id.text);
    text.setText(YOUR_STRING_HERE, TextView.BufferType.NORMAL);
    //rest of the code
}

在Android中,您无法使用system.out.println()在屏幕上输出字符串。你必须使用Android提供的(文本视图,对话框,Toast等)。请阅读有关创建UI的文档。

要在logcat中打印内容,只需使用:

//declare this at the top of your activity
final static String MYTAG = "MyApp";

然后,每当您想在logcat中打印内容时,都可以使用Log.d()。

Log.d(MYTAG, "Whatever content you want to put here");

最新更新