Java 在主if语句中使用返回字符串比较方法
我创建了一个在linux服务器上执行命令的apiType方法。该方法的结果应在我的主类中用于执行类或其他类,具体取决于结果是app2还是app3 linux命令cat/opt/pcu/bin/version | grep PRODUCT | cut-d'-f2的结果是app2或app3 所以我的问题是如何在我的主类中调用和使用方法的结果 或者我做错了什么或者我在代码中遗漏了什么Java 在主if语句中使用返回字符串比较方法,java,Java,我创建了一个在linux服务器上执行命令的apiType方法。该方法的结果应在我的主类中用于执行类或其他类,具体取决于结果是app2还是app3 linux命令cat/opt/pcu/bin/version | grep PRODUCT | cut-d'-f2的结果是app2或app3 所以我的问题是如何在我的主类中调用和使用方法的结果 或者我做错了什么或者我在代码中遗漏了什么 public class Api { private final static String version
public class Api {
private final static String version = "v2";
private final static String path = FileSystems.getDefault().getPath(".").toAbsolutePath().getParent().toString();
public String apiType() throws Exception {
try {
Exec exec = new Exec();
exec.setCommand("cat /opt/pcu/bin/version | grep PRODUCT | cut -d' ' -f2");
exec.setLogPath(path);
exec.run("apiType");
exec.join(200);
Vector<String> output = exec.getOutput(false);
return output.get(0); //this should return "app2" or "app3"?!
} catch (Exception e) {
System.out.println("Failed to run command");
throw e;
}
}
public static void main(String[] args) {
if (args.length == 0) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy/hh:mm:ss");
System.out.println(
"\n\n==================================== TestAPI program ====================================\n");
System.out.println("Date: " + dateFormat.format(date.getTime()) + " " + version);
System.out.println(
"\n==============================================================================================\n\n");
Console console = System.console();
String user = console.readLine("Username: ");
String password = new String((console.readPassword("Password: ")));
String testID = console.readLine("TestID: ");
String pattern = "[Tt]?(\\d+)";
Pattern pat = Pattern.compile(pattern);
Matcher m = pat.matcher(testID);
if (!m.matches()) {
System.out.println("Test ID doesn't have a valid format");
return;
}
testID = m.group(1);
String csvFilePath = console.readLine("CSV Test File: ");
if (????.equals("app2")) {
TestApi2 test = new TestApi2(user, password, testID, csvFilePath);
test.runTest();
} else if (????.equals("app3")) {
TestApi3 test2 = new TestApi3(user, password, testID, csvFilePath);
test2.runTest();
} else {
System.out.println("Unknown");
}
} else if (args.length == 1 && args[0].equalsIgnoreCase("--help")) {
}
}
}
你需要建立一个Api 然后调用该方法并将其返回值赋给字符串
String apiType = api.apiType();
此时,您可以使用新创建的字符串apiType检查返回值
if (apiType.equals("app2")) {
// ...
} else if (apiType.equals("app3")) {
// ...
}
我假设main方法只用于测试类本身,所以我假设您实际上不想使apiType本身成为静态的。我看不出您在哪里调用apiType。当然,您需要调用它并使用它的返回值。您可以将它设置为静态,然后main(也是静态的)可以在没有对象的情况下调用它。公共静态字符串apiType{…}所以您创建了一个调用系统命令的方法,返回一个向量,该向量在其中仍然存在,并找到一个应用程序名,您的问题是如何调用一个方法?
if (apiType.equals("app2")) {
// ...
} else if (apiType.equals("app3")) {
// ...
}