目次
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;/* デスクトップパスの取得 */
Path desktopPath = null;
Path userHomePath = Paths.get(System.getProperty("user.home"));
String desktopPathString;
for (String name : new String[] {"Desktop", "デスクトップ"}) {
desktopPath = userHomePath.resolve(name);
if (Files.isDirectory(desktopPath)) {
desktopPathString = desktopPath.toString();
break;
} else {
desktopPath = null;
}
}
if (desktopPath == null) {
desktopPathString = userHomePath.toString();
}
/* ファイルのダウンロード */
String zipURLString = "https://www.sunday-programmer.com/sample.zip"; // ダウンロード元ファイルのURL
String zipPathString = desktopPathString + File.separator + "sample.zip"; // ダウンロード先ファイルのパス
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(zipURLString).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(zipPathString)) {
int bytes;
byte[] dataBuffer = new byte[16384];
while ((bytes = bufferedInputStream.read(dataBuffer)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytes);
}
} catch (IOException e) {
System.out.println("ファイルのダウンロード中にエラーが発生しました! (" + e.getMessage() + ")");
}