1、电脑没装阅读器。
2、文件加密了。
3、对应的下载工具不支持。
4、Java类文件是Java程序的二进制表示形式。每一个类文件代表一个类或者接口。不可能在一个类文件中放入多个类或者接口。这样就使得无论类文件是在哪一种平台上生成,都可以在任何主机上执行。
主要是 URL 和 HttpURLConnection 类的运用,看代码:
import java.io.DataInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
public class HttpDownloader {
private static final String REMOTE_FILE_URL = "http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf"
private static final String LOCAL_FILE_PATH = "D:/some.pdf" // 改成你保存 文件的路径
public static void main(String[] args) {
new HttpDownloader(REMOTE_FILE_URL, LOCAL_FILE_PATH).download()
}
private String remoteFileUrl
private String localFilePath
public HttpDownloader(String remoteFileUrl, String localFilePath) {
this.remoteFileUrl = remoteFileUrl
this.localFilePath = localFilePath
}
public void download() {
try {
URL url = new URL(remoteFileUrl)
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection()
httpURLConnection.setConnectTimeout(5 * 1000) // 5000 毫秒内没有连接上 则放弃连接
httpURLConnection.connect() // 连接
System.out.println("连接 URL 成功~")
int fileLenght = httpURLConnection.getContentLength()
System.out.println("文件大小:" + (fileLenght / 1024.0) + " KB")
System.out.println("开始下载...")
try (DataInputStream dis = new DataInputStream(httpURLConnection.getInputStream())
FileOutputStream fos = new FileOutputStream(localFilePath)) {
byte[] buf = new byte[10240] // 根据实际情况可以 增大 buf 大小
for (int readSize (readSize = dis.read(buf)) > 0) {
fos.write(buf, 0, readSize)
}
System.out.println("下载完毕~")
} catch (IOException ex) {
System.out.println("下载时出错")
}
httpURLConnection.disconnect()
} catch (IOException ex) {
System.out.println("URL 不存在或者连接超时")
}
}
}