我有一些代码可以从文本文件中读取输入并将其转换为鼠标移动。问题是,一段时间文件变空后,它返回No Line Found Error。我该如何防止这种情况?我试过检查它是否为空,但是没有用。这是代码:
import java.awt.Robot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class JavaRobotExample {
public static void main(String... args) throws Exception {
while (true) {
Thread.sleep(3);
BufferedReader br = new BufferedReader(new FileReader("W:/Mouse/X.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("W:/Mouse/Y.txt"));
if (br.readLine() == null || br2.readLine() == null) {
System.out.println("No errors, and file empty");
Robot robot3 = new Robot();
robot3.mouseMove(0, 0);
continue;
}
Scanner file = new Scanner(new File("W:/Mouse/X.txt"));
String x_contents = file.nextLine();
file.close();
System.out.println(x_contents);
Scanner yfile = new Scanner(new File("W:/Mouse/Y.txt"));
String y_contents = yfile.nextLine();
file.close();
System.out.println(y_contents);
int x_int = Integer.parseInt(x_contents);
int y_int = Integer.parseInt(y_contents);
Robot robot = new Robot();
robot.mouseMove(x_int, y_int);
}
}
}
答案 0 :(得分:3)
不要选中br
或br2
,而是使用方法file
检查Scanner
类型的hasNextLine()
。
if (file.hasNextLine()) ...