我有一个输入流来检查我是否打开了某个 CAD 文件。我通过使用输入流运行具有我要检查的名称的任务列表命令来执行此操作。我目前有一个 boolean 值,如果特定 CAD 文件未打开,则返回 true。如果 CAD 文件已打开,则返回 false。但是,我希望它能够循环执行此操作,直到 CAD 文件打开,因为现在我必须继续运行它才能使其正常工作。我还需要能够从单独的类中检查这个 boolean 值。我现在把它放在我的主目录中,这样我就可以测试它。我的代码看起来像这样...
public class AutoCadCheck {
public static void main(String[] argv) throws Exception {
String notOpen = "INFO: No tasks are running which match the specified criteria";
StringBuilder textBuilder = new StringBuilder();
String command = "tasklist /fi \"windowtitle eq Autodesk AutoCAD 2017 - [123-4567.dwg]";
int i;
InputStream myStream = Runtime.getRuntime().exec(command).getInputStream();
while ((i = myStream.read()) != -1) {
textBuilder.append((char) i);
}
String output = textBuilder.toString();
boolean logical = output.contains(notOpen);
if (logical) {
System.out.println("DWG Not Open");
} else {
System.out.print(output);
}
myStream.close();
}
}
我的另一个类将有一个“if 语句”来检查我的 boolean “逻辑”是否为假,如果是,则打印一些内容。我已经尝试了所有我能想到的方法,但我无法让它按照我想要的方式运行。我发现的所有其他涉及循环输入流的事情并不真正适用于我的情况。所以希望有人可以帮助我实现我想做的事情。
最佳答案
我首先将所有内容从 main 中移出并转移到不同的类中。这将使检索值和调用特定函数变得更容易。然后在main中创建该类的对象。完成后,我将为 boolean 变量创建一个 get 方法。现在重点关注循环。在 main 中创建对象后,在 main 内部创建一个条件循环,该循环调用您需要的函数,直到满足不同的条件。文件打开后可能会满足此条件。满足条件后,它退出到依赖于另一个条件(例如用户输入)的另一个循环。
public class AutoCadCheck {
public static void main(String[] argv) throws Exception {
AutoCadFile file = new AutoCadFile();
//loop 1
//Some conditional so the program will
//continue to run after the file has been found.
// while(){
//loop 2
//check to see if the file is open or not
//while(logical){
//}
//}
}
}
其他类
import java.io.IOException;
import java.io.InputStream;
public class AutoCadFile {
private String notOpen;
private StringBuilder textBuilder;
private String command;
private int i;
private InputStream myStream;
private String output;
private boolean logical;
public AutoCadFile() {
notOpen = "INFO: No tasks are running which match the specified criteria";
textBuilder = new StringBuilder();
command = "tasklist /fi \"windowtitle eq Autodesk AutoCAD 2017 - [123-4567.dwg]";
output = textBuilder.toString();
logical = output.contains(notOpen);
try {
myStream = Runtime.getRuntime().exec(command).getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void checkForFileOpen() {
try {
while ((i = myStream.read()) != -1) {
textBuilder.append((char) i);
}
if (logical) {
System.out.println("DWG Not Open");
} else {
System.out.print(output);
}
myStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean getFileBoolean() {
return logical;
}
}
关于Java 循环输入流直到 boolean = false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48351248/