通过使用java代码传递URL来下载文件
我正在尝试在java中编写一个代码,用户提供一个url链接,程序采用url链接并按原样下载一个网页并保存在特定位置…同样可以在网页上保存为…选项。
请任何人帮助我
提前致谢
//示例url: http : //www.novell.com/coolsolutions/tools/downloads/ntradping.zip
import java.io.*; import java.net.*; public class UrlDownload { final static int size = 1024; public static void fileUrl(String fAddress, String localFileName, String destinationDir) { OutputStream outStream = null; URLConnection uCon = null; InputStream is = null; try { URL url; byte[] buf; int byteRead, byteWritten = 0; url = new URL(fAddress); outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName)); uCon = url.openConnection(); is = uCon.getInputStream(); buf = new byte[size]; while ((byteRead = is.read(buf)) != -1) { outStream.write(buf, 0, byteRead); byteWritten += byteRead; } System.out.println("Downloaded Successfully."); System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void fileDownload(String fAddress, String destinationDir) { int slashIndex = fAddress.lastIndexOf('/'); int periodIndex = fAddress.lastIndexOf('.'); String fileName = fAddress.substring(slashIndex + 1); if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) { fileUrl(fAddress, fileName, destinationDir); } else { System.err.println("path or file name."); } } public static void main(String[] args) { if (args.length == 2) { for (int i = 1; i < args.length; i++) { fileDownload(args[i], args[0]); } } else { } } }
它正在全力以赴。
您可以使用Java URL API在URL上获取输入流,然后从中读取输入流并在文件上写入输出流。
请参阅从URL读取数据 , 写入文件
看看HtmlParser 。 它有一些function可以帮助您从网页中提取资源。
- 静态块未在JDK 7中执行,“未找到主要方法”,但在JDK 1.5中有效
- 带有android片段的java.lang.NullPointerException
- Android – Google Drive HTTP请求
- java.lang.reflect.Method线程安全吗?
- 如何确保Java线程以特定顺序运行
- 抽象数据类型和接口
- 渲染期间引发exception:RelativeLayout中不存在循环依赖关系exception详细信息记录在窗口>显示视图>错误日志中
- 平衡使用堆栈检查括号是否在字符串中关闭
- Firebase / Android:将检索到的值从Firebase添加到arraylist会返回空指针exception