0
1

More than 3 years have passed since last update.

【XML】気象庁から地震情報を取得する①

Posted at

気象庁XMLを取得して解析までの道のり

① XMLのダウンロード(今回)
② XMLファイルの解析(次回)

気象庁からXMLファイルを取得する

ダウンロードを実行するクラスを作成する。

XMLDownloader.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class EarthquakeXMLDownloader implements Runnable {

    // 気象庁のリンク(http://www.data.jma.go.jp/developer/xml/feed/eqvol.xml)
    String link;

    // ダウンロードする場所
    File out;

    public EarthquakeXMLDownloader (String link, File out) {
        this.link = link;
        this.out = out;
    }

    @Override
    public void run() {

        try {
            URL url = new URL(link);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            double fileSize = (double)http.getContentLengthLong();
            BufferedInputStream in = new BufferedInputStream(http.getInputStream());
            FileOutputStream fos = new FileOutputStream(this.out);
            BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
            byte[] buffer = new byte[1024];
            double downloaded = 0.00;
            int read = 0;
            double percentDownloaded = 0.00;

            while((read = in.read(buffer, 0, 1024))>= 0) {
                bout.write(buffer, 0, read);
                downloaded += read;
                percentDownloaded = (downloaded*100)/fileSize;
                String percent = String.format("%.4f", percentDownloaded);
                System.out.println("Downloaded " + percent + "of a file.");
            }

            bout.close();
            in.close();
            System.out.println("Download complete.");
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

↑のファイルを実行する。

Main.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {

    public static void main(String[] args) {

        // アウトプットするファイルパスを作成
        // ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmm");
        String fileName = "earthquake_" + now.format(dateTimeFormatter);
        String link = "http://www.data.jma.go.jp/developer/xml/feed/eqvol.xml";

        File out = new File("C:\\pleiades\\workspace\\SAX\\resource\\" + fileName + ".xml");
        // ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

        // 実行する。
        new Thread(new EarthquakeXMLDownloader(link,out)).start();

    }

}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1