那么实现下载的代码如下:
我要把 视频下载到D盘, 存在dv文件夹中,存为123.avi 则路径为 D:/dv/123.avi
// 下载网络文件
int bytesum = 0;
int byteread = 0;
try {
URL url = new URL("http://www.learnEnglish.com/lesson.avi");
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
File fileD =new File("D:/dv");
//如果文件夹不存在则创建
if (!fileD .exists() && !fileD .isDirectory())
{
System.out.println("正在新建目录");
fileD .mkdirs();;
} else
{
System.out.println("目录存在");
}
File file=new File("D:/dv/123.avi");
if(!file.exists())
{
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fs = new FileOutputStream("D:/dv/123.avi");
byte[] buffer = new byte[1204];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
System.out.println("downloaded ok");
PS:获取下载文件的大小:
URL url=new URL(sample.getRawLink());
HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
//根据响应获取文件大小
int fileLength=urlcon.getContentLength(); //这里获取的是字节
double fileLenM=Double.parseDouble(df.format((fileLength/1024.00)/1024.00)); //转为M |