简体   繁体   English

使用 Java(BufferedInputStream、FileOutputStream、Commons IO 库、NIO)从 URL 下载到文件

[英]download from URL to file using Java (BufferedInputStream, FileOutputStream, Commons IO library, NIO)

I have tried all the ways above to download from URL to file in java.我已经尝试了上述所有方法从 URL 下载到 java 中的文件。 All the ways work, they really downloading the files to the correct directory.所有方法都有效,他们确实将文件下载到正确的目录。 There is one issue: The file content always in gibberish.有一个问题:文件内容总是乱码。

File content example:文件内容示例:

"ãˇ¨ΩKìÏ»é&∂ü_˜l¥πUñëôÁ'ªnõ±QõFY˜'h°ë¡@A"Èx¸ëå∂˛Ô2w2y™n¡£Zã{Îdf<Hß;¯·fl˛”ß◊W—„Ãë¸Ùˇˆ…cdÈ?˝√”_?y:2ù¬ß¯˛flˇÎ˙‰)pG“8Ñ#:G1oÅߘÁœ›Àó?~'Ã( 8£èIÑÁ?~π‡ë{«–°$x{£u˘ûÑ•áÉz:íáÚgp8“¡k˝€;‰∞@óˆüüå[”E¡´N:Ø≤?h∞åw∏éψt∑$õWÇâ∞”SÄÁ˝◊?~[ O¬qåpDfl"4‡òfÙX˚ÖCÍÇ" "ãˇ¨ΩKìÏ»é&∂ü_~l¥πUñëôÁ'ªnõ±QõFY~'h°ë¡@A"Èx¸ëå∂˛Ô2w2y™n¡£Zã{Îdf<Hß;¯·f˛"ß◊W— „Ãë¸Ùˇˆ…cdÈ?˝√”_?y:2ù¬ß¯˛fˇÎ˙‰)pG“8Ñ#:G1oÅß~Áœ›Àó?~'Ã( 8£èIÑÁ?~π‡ë{«–° $x{£u˘ûÑ•áÉz:íáÚgp8“¡k˝€;‰∞@óˆüüå[”E¡´N:Ø≤?h∞åw∏éψt∑$õWÇâ∞”SÄÁ˝◊?~[ O¬qåpDFL “4‡òfÙX˚ÖCÍÇ”

Is anyone has any idea why the file dowloaded in that way?有谁知道为什么以这种方式下载文件? Maybe I should try UTF-8 or something else?也许我应该尝试 UTF-8 或其他什么?

My code:我的代码:

    String dirName = "/Users/idanazulay/Desktop/Hotels-river/";
    String fileUrl = null;
    try {
        fileUrl = getHotelReview("en").getBody().getData().getURL();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // downloadFileFromURLUsingNIO(dirName +"\\feed_en2.json", fileUrl);
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    URL httpUrl = new URL(UriUtils.encodePath(fileUrl, "UTF-8"));
    try {
        try {
            in = new BufferedInputStream(httpUrl.openStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fout = new FileOutputStream(dirName + "\\feed_en2.json");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte data[] = new byte[1024];
        int count;
        try {
            while ((count = in.read(data, 0, 1024)) != -1) {
                fout.write(data, 0, count);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } finally {
        if (in != null)
            in.close();
        if (fout != null)
            fout.close();
    }
    System.out.println("completed");
    return "Download completed";

}

// Using Commons IO library
public static void saveFileFromUrlWithCommonsIO(String fileName, String fileUrl)
        throws MalformedURLException, IOException {
    URL httpUrl = new URL(UriUtils.encodePath(fileUrl, "UTF-8"));
    FileUtils.copyURLToFile(httpUrl, new File(fileName));
}
private static void downloadFileFromURLUsingNIO(String fileName,String fileUrl) throws IOException {
      URL url = new URL(fileUrl);
      ReadableByteChannel rbc = Channels.newChannel(url.openStream());
      FileOutputStream fOutStream = new FileOutputStream(fileName);
      fOutStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
      fOutStream.close();
      rbc.close();
     }
     
     

Solved The issue was that the file extension which I downloaded was (.gz - zip).解决问题是我下载的文件扩展名是(.gz - zip)。 and I tried to copy the details while using "BufferedInputStream" - that was wrong because the file content are compressed.我尝试在使用“BufferedInputStream”时复制详细信息 - 这是错误的,因为文件内容被压缩。 I switched between "BufferedInputStream" to "GZipInputStream" and the file download fine.我在“BufferedInputStream”和“GZipInputStream”之间切换,文件下载正常。

Thanks for everyone who helped:)感谢所有帮助过的人:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从java中的url不完整下载文件-使用java NIO - incomplete download of file from url in java - using java NIO Java的。 从BufferedInputStream读取并写入FileOutputStream - Java. Reading from BufferedInputStream and write to FileOutputStream 使用BufferedInputStream读取大文件时,Java文件IO被截断 - Java file IO truncated while reading large files using BufferedInputStream 无法使用org.apache.commons.io Java库下载pdf网站链接 - Unable to download pdf weblinks using org.apache.commons.io java library 当为映射文件打开FileOutputStream时,从java.nio.MappedByteBuffer读取会导致“不安全的内存访问”错误 - Reading from a java.nio.MappedByteBuffer when a FileOutputStream is open for the mapped file causes an “unsafe memory access” error 使用java apache commons下载文件? - Download file using java apache commons? 如何将此方法从使用 java.io.File 转换为 java.nio.file? - How to convert this method from using java.io.File to java.nio.file? 使用FileOutputStream用Java编写文件 - File writing in Java using FileOutputStream 在 Java 中,使用 java.nio 库和 FileChannel,如何从文件加载 Properties 对象? - In Java, using the java.nio library and a FileChannel, how can I load a Properties object from a file? 使用 Java 从 URL 下载 .jar 文件 - Download .jar File From URL Using Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM