在Java中,可以使用URLConnection类来下载文件
在Java中,可以使用URLConnection类来下载文件。以下是一个简单的示例代码:
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.net.URL;
importjava.net.URLConnection;
publicclassFileDownloader{
publicstaticvoiddownloadFile(Stringurl,StringoutputFile){
try{
URLfileUrl=newURL(url);
URLConnectionconnection=fileUrl.openConnection();
InputStreaminputStream=connection.getInputStream();
FileOutputStreamoutputStream=newFileOutputStream(outputFile);
byte[]buffer=newbyte[1024];
intbytesRead;
while((bytesRead=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("Filedownloadedsuccessfully.");
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
downloadFile("http://example.com/file.jpg","file.jpg");
}
}
在上面的示例中,downloadFile
方法接受要下载的文件的URL和要保存到的本地文件的路径作为参数。它使用URLConnection类来打开URL连接并获取输入流,然后使用FileOutputStream类来保存文件内容到本地文件。最后,关闭输入流和输出流并输出下载成功的消息。您可以将要下载的文件的URL和要保存到的本地文件的路径替换为您自己的值。
版权声明
本文仅代表作者观点,不代表博信信息网立场。