我有这种方法,它通过执行命令“busybox”获得的输出获取前 16 个字符
public String busybox_v() throws IOException {
Process p =Runtime.getRuntime().exec("busybox");
InputStream a = p.getInputStream();
InputStreamReader read = new InputStreamReader(a);
BufferedReader in = new BufferedReader(read);
StringBuilder buffer = new StringBuilder();
String line = null;
try {
while ((line = in.readLine()) != null) {
buffer.append(line);
}
} finally {
read.close();
in.close();
}
if (buffer.length()>=16)
{
String result = buffer.toString().substring(0, 15);
}
else
{
}
String result = buffer.toString().substring(0, 15);
return result;
之前,我有这个崩溃
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=15
at java.lang.String.startEndAndLength(String.java:583) at java.lang.String.substring(String.java:1464)
at com.MyPackage.MyApplicationName.Root.busybox_v(Root.java:98)
at com.MyPackage.MyApplicationName.PageFragment$1.onClick(PageFragment.java:101)
at android.view.View.performClick(View.java:4240) at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:110)
at dalvik.system.NativeStart.main(Native Method)
第 98 行对应于 while 的右大括号,然后感谢用户对 Stack Overloflow 的建议,我放置了一个 if-else 来检查长度是否实际上大于或等于 16 个字符,而不会使应用程序崩溃。但是对于当前的代码,应用程序崩溃都是一样的,因为我在另一个类中有这个代码
try {
String myResult=root.busybox_v();
if(myResult!=null&&myResult.length()>0) {
TextView1.setText(Html.fromHtml(("<b><font color=\"#009900\">"+myResult+"</font></b>")));
}
else {
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
你对我如何解决这个问题有什么想法吗?