在Java中可以使用java.net.URL和java.io.InputStream来下载文件内容。以下是一个简单的示例代码:
import java.io.BufferedInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;public class FileDownloader { public static void main(String[] args) { String fileUrl = "https://example.com/file.txt"; String savePath = "downloadedFile.txt"; try { URL url = new URL(fileUrl); InputStream inputStream = new BufferedInputStream(url.openStream()); FileOutputStream fileOutputStream = new FileOutputStream(savePath); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } fileOutputStream.close(); inputStream.close(); System.out.println("File downloaded successfully!"); } catch (IOException e) { e.printStackTrace(); } }}在上面的示例中,我们通过URL类打开URL连接并获取输入流,然后通过FileOutputStream类将文件内容写入本地文件。最后,关闭输入流和输出流。确保替换fileUrl和savePath为你要下载的文件的URL和保存路径。




