使用java下载模板文件的示例代码
时间: 2024-02-06 20:04:16 浏览: 83
Java模板文件下载。
好的,以下是一个使用Java下载模板文件的示例代码:
```
import java.io.*;
import java.net.*;
public class DownloadTemplate {
public static void main(String[] args) {
String fileUrl = "https://www.example.com/template.docx";
String saveDir = "/home/user/Documents/";
try {
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
// Check if response code is OK before downloading
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = conn.getHeaderField("Content-Disposition");
// Get the file name from the content-disposition header
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());
}
// Create file output stream and input stream to download file
String saveFilePath = saveDir + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
// Download the file
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("File downloaded successfully");
} else {
System.out.println("Failed to download file");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例代码可以从指定的URL下载文件,并将文件保存到指定的目录中。请注意,如果您想要下载的模板文件是受保护或需要授权的,则需要添加您的账户信息或令牌到请求头中,以便可以通过授权访问文件。
阅读全文