オンラインリソースに接続し、データを読み取り、特定の情報を解析するJavaプログラムがあります(特定のページを表示しているアクティブなredditアカウントの数です)。
このプロセスを自動化して、特定の間隔で繰り返すようにしたいと考えています (動作しているかどうかを確認するために、間隔を 5 秒に設定しています)。次に、プログラムはこの番号を毎回異なる行でファイルに出力します。私のoutput.txt
ファイルには複数の行があるため、メインループが反復していることはわかっていますが、最初の反復で番号を見つけて出力するだけです。
package redditreader3;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RedditReader3 {
public static void main(String[] args) throws IOException, InterruptedException
{
int i = 1;
String host = args[0]; // www.reddit.com
String resource = args[1]; // /r/toronto/about.json
final int HTTP_PORT = 80;
String command = "GET " + resource + " HTTP/1.1\n" + "Host:" + host
+ "\n\n";
/* This command requests reddit for the source code of the resource in args[1] at its host, args[0] to be printed through HTTP. */
Socket socket = new Socket(host, HTTP_PORT);
InputStream instream = socket.getInputStream();
Scanner in = new Scanner(instream);
OutputStream outstream = socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
File file = new File("output.txt");
FileOutputStream F_outstream = new FileOutputStream(file);
PrintStream F_printstream = new PrintStream(F_outstream);
/* Now that the connection has been established and all of the objects
are connected to each other, the command may be sent and the data
transfer may begin. */
String ActiveAccountsData = ("\"accounts_active\": (\\d+)");
String ActiveAccountsDataFOUND;
Pattern ActiveAccountsPattern = Pattern.compile(ActiveAccountsData);
Matcher ActiveAccountsMatcher;
String input;
while(i <= 4)
{
out.print(command);
out.flush();
while(in.hasNextLine())
{
input = in.nextLine();
ActiveAccountsMatcher = ActiveAccountsPattern.matcher(input);
if(ActiveAccountsMatcher.find())
{
ActiveAccountsDataFOUND = ActiveAccountsMatcher.group(1);
F_printstream.println(ActiveAccountsDataFOUND);
break;
}
}
i++;
F_printstream.println();
Thread.sleep(5000);
}
}
}
値がどこかにスタックしていて更新する必要があるのではないかと考えin.hasNextLine()
ていましたが、Web サイトからの入力の先頭に戻すメソッドが見つかりません。