帮我写一段java代码,用于输入一个文件链接并下载到当前目录
时间: 2023-05-17 10:06:16 浏览: 45
好的,以下是Java代码示例:
import java.io.*;
import java.net.*;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String saveDir = "./";
try {
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());
}
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully!");
} else {
System.out.println("Error in file download!");
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}