我在制作一个程序,可以从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");
}
}
那我该怎么解决呢?需要使用其他方式下载吗?