首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文件下载与java -文件损坏

文件下载与java -文件损坏
EN

Stack Overflow用户
提问于 2016-09-09 09:20:49
回答 4查看 6.6K关注 0票数 0

这是我的代码,我写这个是为了下载mp3苍蝇,视频文件和图像。我用FileOutputStream来处理文件。所有文件都下载得很好。mp3文件是working..but图像,视频被破坏

代码语言:javascript
复制
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();
    }
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-09-09 09:39:21

我试过你的惯例了。对我来说很好。

我使用了URL

"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。您必须在浏览器中使用“查看图像”或“复制图像位置”。

票数 1
EN

Stack Overflow用户

发布于 2016-09-09 09:38:10

看看像Apache IO这样的库。它有许多助手方法,如重定向流

票数 1
EN

Stack Overflow用户

发布于 2016-09-09 09:40:51

你可以试试这个代码,

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39408127

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档