java - 使用 Java 代码未完全下载文件

标签 java

我正在使用 Java 下载文件,我使用了三个不同的代码片段,我将在此处发布它们。但所有人的结果都是一样的。他们都部分下载文件,因此文件无法打开,因为文件未完全下载。我应该如何解决这个问题。

我的第一个代码:

public class FileDownloader {

 final static int size=1024;
 public static void main(String[] args){
     fileUrl("http://textfiles.com/holiday","holiday.tar.gz","C:\\Users\\Me\\Downloads");

 }

    public static void  fileUrl(String fAddress, String localFileName, String destinationDir) {
    OutputStream outStream = null;
    URLConnection  uCon = null;

    InputStream is = null;
    try {
        URL Url;
        byte[] buf;
        int ByteRead,ByteWritten=0;
        Url= new URL(fAddress);
        outStream = new BufferedOutputStream(new
        FileOutputStream(destinationDir+"\\"+localFileName));

        uCon = Url.openConnection();
        is = uCon.getInputStream();
        buf = new byte[size];
        while ((ByteRead = is.read(buf)) != -1) {
            outStream.write(buf, 0, ByteRead);
            ByteWritten += ByteRead;
        }
        System.out.println("Downloaded Successfully.");
        System.out.println("File name:\""+localFileName+ "\"\nNo ofbytes :" + ByteWritten);
    }catch (Exception e) {
        e.printStackTrace();
        }
    finally {
            try {
            is.close();
            outStream.close();
            }
            catch (IOException e) {
        e.printStackTrace();
            }
        }
 }






}

我使用的第二个代码:

public class downloadFile {

public static void main(String[]args){
    downloadFile dfs = new downloadFile();
    dfs.downloadFileAndStore("C:\\Users\\Me\\Downloads","Sign&ValidateVersion2.docx");

}

    /**
     * download and save the file
     * @param fileUrl: String containing URL 
     * @param destinationDirectory : directory to store the downloaded file
     * @param fileName : fileName without extension
     */
    public void downloadFileAndStore(String destinationDirectory,String fileName){
    //  URL url = null;
        FileOutputStream fos = null;

            //convert the string to URL
             try {
        //      url = new URL(fileUrl);

                 HttpClient client = HttpClientBuilder.create().build();
                 HttpGet request = new HttpGet("https://mail.uvic.ca/owa/#path=/mail");
                 HttpResponse response = client.execute(request);
                 if(response.getEntity().getContent().read()==-1){
                     Log.error("Response is empty");
                 }
                 else{

                 BufferedReader rd = new BufferedReader(new InputStreamReader(response
                             .getEntity().getContent()));
                 StringBuffer result = new StringBuffer();
                 String line = "";
                 while ((line = rd.readLine()) != null) {
                     result.append(line);
                 }
                 fos = new FileOutputStream(destinationDirectory + "\\" + fileName);
                 fos.write(result.toString().getBytes());
                 fos.close();
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                 Log.error("PDF " + fileName + " error: " + e.getMessage());
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                 Log.error("PDF " + fileName + " error: " + e.getMessage());
            } catch (UnsupportedOperationException e) {
                // TODO Auto-generated catch block
                Log.error("PDF " + fileName + " error: " + e.getMessage());
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                Log.error("PDF " + fileName + " error: " + e.getMessage());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.error("PDF " + fileName + " error: " + e.getMessage());
            }

}

}

我使用的第三个代码:

public class download {

public static void main(String[] args) {
    download dfs = new download();
    dfs.downloadFile();

}
public void downloadFile(){
    try {
        IOUtils.copy(
                new URL("https://archive.org/details/alanoakleysmalltestvideo").openStream(), 
                new FileOutputStream("C:\\Users\\Me\\Downloads\\spacetestSMALL.wmv")
            );
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}



}

我必须下载一个视频文件,大约有6-7 MB,但是我已经将这三个代码用于小文本文件和其他类型,但它不起作用。有人有什么想法吗?

最佳答案

我尝试了你的第一个例子,它对我有用。我猜你误解了你实际上在做什么。与

fileUrl("http://textfiles.com/holiday","holiday.tar.gz","C:\\Users\\Me\\Downloads");

您正在将 textfiles.com/holiday 的 HTML 页面下载到名为“holiday.tar.gz”的文件中。实际的 tar 存档的 URL 为 archives.textfiles.com/holiday.tar.gz。

在您的评论中,您说您实际上想要下载 archive.org/details/alanoakleysmalltestvideo 下的视频,但使用此 URL,您只需下载嵌入视频的 HTML 页面(成功)即可。

如果您查看 HTML 源代码,您可以找到实际的视频 URL,例如 archive.org/download/alanoakleysmalltestvideo/spacetestSMALL_512kb.mp4,并使用现有代码成功下载它。

关于java - 使用 Java 代码未完全下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487316/

相关文章:

java - Java EE 有哪些异步通信方法?

java - 调用 contains 时无法重写 Java 上的 Equals 方法

java - 如何在单击 ListView 时检索多个数据?

java - 如何在 Java 中实现成员明智比较?

java - 为什么 FileInputStream 读取的数组越大越慢

Java 音频未加载。 toURI 不工作?

java - 动态字节码执行

java - 获取有关 CPU 的人类可读信息

java - 如何将 128 到 255 的字节映射到等效的 UTF16-LE 代理项对

java - 收到SIGTERM后如何正确关闭Spring bean?