① Télécharger XML (cette fois) ② Analyse du fichier XML (la prochaine fois)
Créez une classe pour effectuer le téléchargement.
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 {
//Lien vers l'Agence météorologique (http)://www.data.jma.go.jp/developer/xml/feed/eqvol.xml)
String link;
//Où télécharger
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();
}
}
}
Exécutez le fichier ci-dessus.
Main.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
//Créer un chemin de fichier vers la sortie
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
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");
// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//Exécuter.
new Thread(new EarthquakeXMLDownloader(link,out)).start();
}
}
Recommended Posts