如何使用Java在线下载mp3文件?

7
我使用以下方法下载了一个mp3文件: http://online1.tingclass.com/lesson/shi0529/43/32.mp3, 但是我遇到了以下错误: java.io.FileNotFoundException: http:\online1.tingclass.com\lesson\shi0529\43\32.mp3(文件名、目录名或卷标语法不正确)
  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(); }
  }

如果我手动从浏览器中执行该操作,则文件是存在的,我想知道为什么它没有起作用,以及正确的操作方式是什么?
弗兰克
3个回答

18

使用老式的Java IO,但你可以将其映射到你正在使用的NIO方法中。关键是使用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();

真是太棒了! - Cole Henrich

2

FileInputStream仅用于访问本地文件。如果您想访问URL的内容,可以设置一个URLConnection或使用类似以下代码的方式:

URL myUrl = new URL("http://online1.tingclass.com/lesson/shi0529/43/32.mp3");
InputStream myUrlStream = myUrl.openStream();
ReadableByteChannel myUrlChannel = Channels.newChannel(myUrlStream);

FileChannel destinationChannel=new FileOutputStream(To_File).getChannel();
destinationChannel.transferFrom(myUrlChannel, 0, sizeOf32MP3);

或者更简单地,只需从myUrlStream创建一个BufferedInputStream,并循环执行读/写操作,直到在myUrlStream上找到EOF。
祝好, 安德烈

2
当您创建一个FileInputStream时,您总是访问本地文件系统。相反,您应该使用URLConnection来访问通过HTTP传输的文件。
这一点的标志是斜杠/已经变成了反斜杠\

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接