可下载图片、jar包、以及各种文件
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
public class Filedownload {
public static void main(String[] args) {
String fileUrl = "http://xx.xx.xx.xx:yyyy/uuuu.tar"; // 替换为要下载的文件的URL
String fileSuffix = fileUrl.substring(fileUrl.lastIndexOf("."));
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + fileSuffix;
File outputPath = new File("D:\\file\\"+finalFileName); //保存到本地的文件路径
try {
File dir = outputPath.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
outputPath.createNewFile();//创建文件
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream outputStream = new FileOutputStream(outputPath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("下载文件成功,目录:" + outputPath);
} else {
System.out.println("下载文件失败,错误码:" + connection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}