这是我的代码。我写这个是为了下载 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();
}
最佳答案
我尝试了你的惯例。对我来说效果很好。
我使用了网址
"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,而不是上面的。您必须在浏览器中使用“查看图像”或“复制图像位置”。
关于java - 使用 java 下载文件 - 文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408127/