import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class DownloadFile { public static void main(String[] args) throws Exception { String url = "http://example.com/file.txt"; // 服务器上文件的URL String fileName = "file.txt"; // 文件名 URL fileUrl = new URL(url); URLConnection connection = fileUrl.openConnection(); InputStream inputStream = connection.getInputStream(); // 将服务器上的文件保存到本地 FileOutputStream outputStream = new FileOutputStream(fileName); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("文件下载完成"); } }改为从输入流获取文件名字下载
时间: 2024-03-31 09:36:36 浏览: 90
以下是修改后的代码:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class DownloadFile {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要下载的文件的URL:");
String url = scanner.nextLine(); // 服务器上文件的URL
System.out.print("请输入要保存的文件名:");
String fileName = scanner.nextLine(); // 文件名
URL fileUrl = new URL(url);
URLConnection connection = fileUrl.openConnection();
InputStream inputStream = connection.getInputStream();
// 将服务器上的文件保存到本地
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件下载完成");
}
}
修改后的代码中,使用了Scanner类获取用户输入的文件URL和保存的文件名,然后将其传入下载代码中。这样就可以从输入流获取文件名字下载了。
阅读全文