在Java中,可以使用java.net.URL
类来下载文件。下面是一个简单的示例代码:
importjava.io.BufferedInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.URL;
publicclassFileDownloader{
publicstaticvoiddownloadFile(StringfileUrl,StringsavePath)throwsIOException{
URLurl=newURL(fileUrl);
BufferedInputStreaminputStream=newBufferedInputStream(url.openStream());
FileOutputStreamoutputStream=newFileOutputStream(savePath);
byte[]buffer=newbyte[1024];
intbytesRead;
while((bytesRead=inputStream.read(buffer,0,1024))!=-1){
outputStream.write(buffer,0,bytesRead);
}
outputStream.close();
inputStream.close();
}
publicstaticvoidmain(String[]args){
StringfileUrl="https://example.com/file.txt";
StringsavePath="/path/to/save/file.txt";
try{
downloadFile(fileUrl,savePath);
System.out.println("文件下载完成");
}catch(IOExceptione){
e.printStackTrace();
}
}
}
在上面的示例代码中,downloadFile
方法接受文件的URL和保存的路径作为参数,通过URL
类打开输入流并使用BufferedInputStream
进行缓冲读取,然后使用FileOutputStream
写入到指定的文件中。最后,关闭输入流和输出流。
在main
方法中,你可以替换fileUrl
和savePath
为你要下载的文件的URL和保存的路径。