使用java写一段代码:.循环发送"pwd"命令并等待1秒,直到返回当前路径,退出循环;
时间: 2023-06-03 18:03:15 浏览: 52
好的,以下是代码实现:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
String cmd = "pwd"; // 待执行的命令
String currentPath = ""; // 当前路径
while (!currentPath.equals(getCurrentPath())) {
// 如果当前路径不等于上一次获取的路径,则继续执行命令
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmd);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
currentPath = reader.readLine();
System.out.println(currentPath); // 打印当前路径
try {
Thread.sleep(1000); // 等待1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static String getCurrentPath() throws IOException {
// 获取当前路径
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("pwd");
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
return reader.readLine();
}
}
```
这段代码会循环执行"pwd"命令,每次执行后等待1秒,直到获取到的当前路径与上一次获取的路径相同时,退出循环。