java主线程下载

public class Download {                                                         // 主线程下载

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {             // 主函数
  String path = new String(http://192.168.1.122/haha/GEM.mp3);     // 下载的资源的地址,这里用的是tomcat开启的本地服务器。
  new Download().Downloadmp3(path);                                          // 将资源地址传入,写一个Downloadmp3(Sting path)方法。
 }

 private void Downloadmp3(String path) throws IOException {
  URL url = new URL(path);                                                      // 新建一个URL对象,通过URL中的openConnection()方法得到资源连接对象。
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setReadTimeout(5000);                                             // 设置连接超时
  conn.setRequestMethod("GET");                                       // 提交方式为GET
  int Length=conn.getContentLength();                                // 得到资源长度
  if(conn.getResponseCode()==200){                                  // if连接成功
  InputStream input = conn.getInputStream();                     // 资源输入流
  File file=new File("GEM.mp3");                                                // 新建名为GEM.mp3文件,默认地址工程目录
  RandomAccessFile accessFile = new RandomAccessFile(file, "rwd"); 
  accessFile.setLength(Length);                                                     //文件长度
  FileOutputStream output = new FileOutputStream(file);             //新建该文件输出流
 
  int flog = 0;   
  byte[] buffer = new byte[4*1024];
  while ((flog=input.read(buffer)) != -1) {                                    //输入流不为空则将内容写入文件
   accessFile.write(buffer, 0, flog);
  }
  output.flush();
  input.close();                                                                               //关闭输入流
  
  }
  else {
   System.out.println("下载失败!");
  }
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值