共計(jì) 835 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中實(shí)現(xiàn) ping 功能可以通過執(zhí)行系統(tǒng)命令來調(diào)用操作系統(tǒng)提供的 ping 命令。以下是一個(gè)示例代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PingExample {public static void main(String[] args) {String ipAddress = "127.0.0.1";
try {Process process = Runtime.getRuntime().exec("ping " + ipAddress);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {System.out.println(line);
}
int exitValue = process.waitFor();
if (exitValue == 0) {System.out.println("Ping successful");
} else {System.out.println("Ping failed");
}
} catch (IOException | InterruptedException e) {e.printStackTrace();
}
}
}
在上面的代碼中,我們通過 Runtime.getRuntime().exec("ping " + ipAddress)
來執(zhí)行 ping 命令,然后讀取 ping 命令的輸出并打印出來。最后通過 process.waitFor()
方法獲取 ping 命令的退出值,如果退出值為 0 則表示 ping 成功,否則表示 ping 失敗。
請(qǐng)注意,執(zhí)行系統(tǒng)命令存在一定的安全風(fēng)險(xiǎn),需要謹(jǐn)慎處理輸入?yún)?shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完