如何使用Java在线下载mp3文件? [英] How to use Java to download a mp3 file online?

查看:469
本文介绍了如何使用Java在线下载mp3文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法下载mp3文件:
http://online1.tingclass.com/lesson/shi0529/43/32.mp3

I used the following method to download an mp3 file at : http://online1.tingclass.com/lesson/shi0529/43/32.mp3

但是我收到以下错误:

java.io.FileNotFoundException:http:\online1.tingclass.com\lesson\shi0529\43\32.mp3(文件名,目录名或卷标签语法不正确)

java.io.FileNotFoundException: http:\online1.tingclass.com\lesson\shi0529\43\32.mp3 (The filename, directory name, or volume label syntax is incorrect)

  public static void Copy_File(String From_File,String To_File)
  {   
    try
    {
      FileChannel sourceChannel=new FileInputStream(From_File).getChannel();
      FileChannel destinationChannel=new FileOutputStream(To_File).getChannel();
      sourceChannel.transferTo(0,sourceChannel.size(),destinationChannel);
      // or
      //  destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
      sourceChannel.close();
      destinationChannel.close();
    }
    catch (Exception e) { e.printStackTrace(); }
  }

然而,如果我手工从浏览器中执行,文件就在那里,我不知道为什么它不起作用,什么是正确的方法?

Yet if I do it from a browser by hand, the file is there, I wonder why it didn't work, and what's the right way to do it ?

Frank

推荐答案

使用旧版Java IO,但您可以将其映射到您正在使用的NIO方法。关键是使用URLConnection。

Using old-school Java IO, but you can map this to the NIO method you are using. Key thing is use of URLConnection.

    URLConnection conn = new URL("http://online1.tingclass.com/lesson/shi0529/43/32.mp3").openConnection();
    InputStream is = conn.getInputStream();

    OutputStream outstream = new FileOutputStream(new File("/tmp/file.mp3"));
    byte[] buffer = new byte[4096];
    int len;
    while ((len = is.read(buffer)) > 0) {
        outstream.write(buffer, 0, len);
    }
    outstream.close();

这篇关于如何使用Java在线下载mp3文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆