这是我的code.i写这个下载mp3苍蝇,视频文件&图片。 我使用FileOutputStream来处理文件.. 所有文件下载都很好.. mp3文件正在运行..但图像和视频已损坏
private void download(String fileURL, String destinationDirectory,String name) throws IOException {
// File name that is being downloaded
String downloadedFileName = name;
// Open connection to the file
URL url = new URL(fileURL);
InputStream is = url.openStream();
// Stream to the destionation file
FileOutputStream fos = new FileOutputStream(destinationDirectory + "/" + downloadedFileName);
// Read bytes from URL to the local file
byte[] buffer = new byte[4096];
int bytesRead = 0;
System.out.println("Downloading " + downloadedFileName);
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
// Close destination stream
fos.close();
// Close URL stream
is.close();
}
答案 0 :(得分:1)
查看Apache IO等库。 它有许多辅助方法,例如redirecting streams。
答案 1 :(得分:1)
我尝试了你的日常生活。对我来说很好。
我使用了网址
“http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3”
并获得了一个可播放的MP3文件,正好是1,430,174字节。
接下来我尝试了JPEG:
“http://weknowyourdreams.com/images/beautiful/beautiful-01.jpg”
工作正常。
我怀疑发生的事情是您错误地使用了网页的URL而不是音频/视频/图片文件。例如,如果您使用了URL
“http://weknowyourdreams.com/image.php?pic=/images/beautiful/beautiful-01.jpg”
而不是上面的那个,你将得不到合适的JPG。您必须在浏览器中使用“查看图像”或“复制图像位置”。
答案 2 :(得分:0)
您可以尝试使用此代码,
URLConnection con = new URL(fileURL).openConnection();
InputStream is = con.getInputStream();
OutputStream fos = new FileOutputStream(new File(destinationDirectory + "/" + name));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) > 0) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
答案 3 :(得分:0)
你需要使用BufferedOutputStream。
BufferedOutputStream bos = new BufferedOutputStream(fos );
像这样:
private void download(String fileURL, String destinationDirectory,String name) throws IOException {
// File name that is being downloaded
String downloadedFileName = name;
// Open connection to the file
URL url = new URL(fileURL);
InputStream is = url.openStream();
// Stream to the destionation file
FileOutputStream fos = new FileOutputStream(destinationDirectory + "/" + downloadedFileName);
BufferedOutputStream bos = new BufferedOutputStream(fos );
// Read bytes from URL to the local file
byte[] buffer = new byte[4096];
int bytesRead = 0;
System.out.println("Downloading " + downloadedFileName);
while ((bytesRead = is.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
// Close destination stream
bos.close();
// Close URL stream
is.close();
}