java下载二进制文件
时间: 2023-09-22 13:15:02 浏览: 189
要下载二进制文件,您可以使用Java的URL和URLConnection类。以下是一个简单的示例:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class BinaryDownloader {
public static void main(String[] args) throws IOException {
// URL of the binary file to download
String fileUrl = "https://example.com/mybinaryfile.bin";
// Open a connection to the URL
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
// Get the input stream and wrap it in a buffered input stream
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
// Create the output file stream
FileOutputStream out = new FileOutputStream("mybinaryfile.bin");
// Read bytes from the input stream and write them to the output stream
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
// Close the streams
out.close();
in.close();
}
}
```
在这个示例中,我们使用URL和URLConnection类打开连接到二进制文件的URL。然后,我们获取输入流并将其包装在缓冲输入流中。接下来,我们创建一个文件输出流来写入二进制文件。最后,我们循环读取输入流的字节并将它们写入输出流中,直到读取完整个文件。最后,我们关闭输入和输出流。
阅读全文