Fra*_*ank 5 java mp3 file download
我使用以下方法下载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(); }
}
Run Code Online (Sandbox Code Playgroud)
然而,如果我手动从浏览器中执行此操作,文件就在那里,我想知道它为什么不起作用,以及正确的方法是什么?
坦率
Joe*_*oel 14
使用旧式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();
Run Code Online (Sandbox Code Playgroud)