should be more than a line feed
** Android development of two identical "string", why in if judgment is not valid?
**
事情是这样的,我有一个项目需要用到shell脚本,常规地用了Runtime.getRuntime().exec()这个方法,并且通过输出流获取到了脚本的echo,并将 echo 的字符串返回。这么说可能不太清楚,举个例子
// shell 脚本
public static final String SHELL_TEST1 = "echo \"ok\"" ;
//执行shell并获取返回值的方法:
/**
* @注解 执行shell命令,并获取shell的返回值
* @param mycmd shell命令
* TODO 也可以执行.sh脚本文件,只需要输入路径即可*/
public static String RunCmd1(String mycmd) {
Process su = null;
// 定义shell返回值
String result = null;
try {
su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes(mycmd + "\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
// 获取shell返回流
BufferedReader br = new BufferedReader(new InputStreamReader(su.getInputStream()));
StringBuffer sb2 = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb2.append(line).append("\n");
System.out.println("==============================循环体中" + result);
}
result = sb2.toString();
// 关闭输入流
br.close();
System.out.println("==============================" + result);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
String s = result.toString();
return s;
}
Above defines the shell statement and the method to execute the shell. Below is a call to
from another class.//在某个按钮的点击事件中调用,假设shell脚本是耗时操作,比如复制文件,所以用到了线程通信
public onClick(View v){
Handler handler = new Handler(Looper.myLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 666){
String isOk = (String) msg.obj;
System.out.println("=========================================handler接收的返回值为:" + isOk);
if (isOk.equals("1")) {
ToastUtil.out(context,"成功").show();
} else {
System.out.println("=========================================handler判断条件不成立" );
}
}
};
new Thread(() -> {
Message msg = new Message();
msg.what = 666;
String s = RunCmd1(SHELL_TEST1 );
System.out.println("====================================================util调用cmd命令得到的返回值为:" + runCmd1);
msg.obj = runCmd1;
handler.sendMessage(msg);
}).start();
}
, run the mobile phone, Logcat shows: < br / >
< div class = "aw - list - img >
When isOk and "1" are the same, why does the program go to the else? Scratching my head! Changed the code, rebooted it. Nothing. Have you ever been in this situation?
0 Answer
should be more than a line feed
Would you like to print the length of isOK and see if there are any extra Spaces or white space characters(such as line breaks etc)
The return value is the string "1", but the length of the print is 2, really strange! How to solve it?
这家伙很懒,什么都没留下...