① XML herunterladen (diesmal) ② Analyse der XML-Datei (nächstes Mal)
Erstellen Sie eine Klasse, um den Download durchzuführen.
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 {
//Link der Meteorologischen Agentur (http)://www.data.jma.go.jp/developer/xml/feed/eqvol.xml)
String link;
//Wo zum Download
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();
}
}
}
Führen Sie die obige Datei aus.
Main.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
//Erstellen Sie einen Dateipfad für die Ausgabe
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
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");
// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//Lauf.
new Thread(new EarthquakeXMLDownloader(link,out)).start();
}
}