gpt4 book ai didi

java - 无法从java中的URL下载文件

转载 作者:搜寻专家 更新时间:2023-10-31 20:10:31 24 4
gpt4 key购买 nike

我正在制作一个从 URL 下载文件的程序。下载总是开始,但没有完成。例如,如果文件大小为 3 MB,程序只下载一半,所以我无法打开下载的文件。但是程序说文件下载成功。

public class FileDownloader {

public static void main (String [] args) throws IOException {

InputStream fileIn;
FileOutputStream fileOut;
Scanner s = new Scanner(System.in);

System.out.println("Enter URL: ");
String urlStr = s.nextLine();

URL url = new URL(urlStr);
URLConnection urlConnect = url.openConnection();
fileIn = urlConnect.getInputStream();

System.out.println("Enter file name: ");
String fileStr = s.nextLine();
fileOut = new FileOutputStream(fileStr);

while (fileIn.read() != -1) {
fileOut.write(fileIn.read());
}
System.out.println("File is downloaded");
}
}

那我该如何解决呢?是否应该使用其他方式下载?

最佳答案

由于

,您正在丢失每个备用 字节
    while (fileIn.read() != -1) {     //1st read
fileOut.write(fileIn.read()); //2nd read - 1st write
}

你读了两次,只写了一次。

你需要做的是

    int x;
while ((x = fileIn.read()) != -1) { //1st read
fileOut.write(x); //1st write
}

这是你的完整代码

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

public class FileDownloader {

public static void main(String[] args) throws IOException {

InputStream fileIn;
FileOutputStream fileOut;
Scanner s = new Scanner(System.in);

System.out.println("Enter URL: ");
String urlStr = s.nextLine();

URL url = new URL(urlStr);
URLConnection urlConnect = url.openConnection();
fileIn = urlConnect.getInputStream();

System.out.println("Enter file name: ");
String fileStr = s.nextLine();
fileOut = new FileOutputStream(fileStr);

int x;
while ((x = fileIn.read()) != -1) {
fileOut.write(x);
}
System.out.println("File is downloaded");

}

关于java - 无法从java中的URL下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31390793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com