我正在尝试用 Java 实现比萨状态显示。因此,Java 文件正在读取 html 文件中的值并打印它。可以通过 php 脚本更改状态: http: //easternmotormall.com/teamdroidco/server/statusUpdater.php
所以脚本将状态写入文件: http ://easternmotormall.com/teamdroidco/server/home.html
Java 文件打印它。但我的主要问题是它只需要显示一次结果,我不确定如何实现它。
这是Java代码:
url = new URL("http://easternmotormall.com/teamdroidco/server/home.html");
try {
System.out.println("Fetching status from the server, please wait..");
String temp = null;
while(true){
URLConnection con = url.openConnection();
BufferedReader dataPtr = new BufferedReader(new InputStreamReader(con.getInputStream()));
// Printing status from Status Updater
String status = dataPtr.readLine();
if (status != null) {
System.out.println(status);
}
dataPtr.close();
Scanner in2 = new Scanner(System.in);
in2.nextLine();
}
}
catch (IOException e) {
System.err.println();
}
}
catch (MalformedURLException e)
{
System.err.println();
}
我在最后暂停了循环,所以它不会继续循环。
我怎样才能使它仅在为文件提供新状态时才打印?
PS。如果有帮助的话,这最终将转换为一个 android 应用程序。
编辑:::::::::::::::::::::::::::::::::::::::::::: 这是编辑的带线程的版本:
url = new URL("http://easternmotormall.com/teamdroidco/server/home.html");
try {
System.out.println("Fetching status from the server, please wait..");
String temp = null;
while(true){
URLConnection con = url.openConnection();
BufferedReader dataPtr = new BufferedReader(new InputStreamReader(con.getInputStream()));
// Printing status from Status Updater
String status = dataPtr.readLine();
if (status != null) {
System.out.println(status);
}
dataPtr.close();
Scanner in2 = new Scanner(System.in);
in2.nextLine();
}
}
catch (IOException e) {
System.err.println();
}
statusThread statusreq = new statusThread();
statusreq.start();
System.out.println("After the thread...");
}
catch (MalformedURLException e)
{
System.err.println();
}
}
class statusThread extends Thread {
// 2. This is the run() method with some sample contents
public void run() {
String status ="", lastStatus ="";
URL url;
try {
url = new URL("http://easternmotormall.com/teamdroidco/server/home.html");
System.out.println("Fetching status from the server, please wait.. (Thread started)");
while(true){
URLConnection con = url.openConnection();
BufferedReader dataPtr = new BufferedReader(new InputStreamReader(con.getInputStream()));
// Printing status from Status Updater
status = dataPtr.readLine();
if (status != null && !status.equals(lastStatus)) {
//new status!
lastStatus = status;
System.out.println(status);
}
else {
// do nothing or log something
}
dataPtr.close();
Scanner in2 = new Scanner(System.in);
in2.nextLine();
}
}
catch (IOException e) {
System.err.println();
}
}
}