使用 java 下载文件 - 文件已损坏

File download with java - Files corrupted

这是我的 code.i 写这篇文章来下载 mp3 flies、视频文件和图像。 我使用 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();
    }

看看 Apache IO 这样的库。 它有许多辅助方法,例如 redirecting streams.

我试过你的程序。适合我。

我用了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 而不是 audio/video/pic 文件。例如,如果您使用 URL

"http://weknowyourdreams.com/image.php?pic=/images/beautiful/beautiful-01.jpg"

而不是上面的那个,你不会得到一个合适的 JPG。您必须在浏览器中使用 "View Image" 或 "Copy Image Location"。

你可以试试这个代码,

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

您需要使用 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();
    }