How to use Java to download a mp3 file online?

大憨熊 提交于 2019-12-09 05:02:42

问题


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

But I got the following error :

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


回答1:


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();



回答2:


When you create a FileInputStream, you always access your local filesystem. Instead, you should use a URLConnection for accessing files over HTTP.

The indicator for this is that the forward slashes / have turned into backward slashes \.




回答3:


FileInputStream is used to access local files only. If you want to access the content of an URL you can setup an URLConnection or use something like this:

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);

Or more simply just make a BufferedInputStream from myUrlStream and cycle the read/write operation until EOF is found on myUrlStream.

Cheers, Andrea



来源:https://stackoverflow.com/questions/3653842/how-to-use-java-to-download-a-mp3-file-online

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!