Упражнение: Копирайте локално няколко WEB страници. WEB страниците и имената на съответстващите файлове се намират в файл с име url-list.txt в следващата форма:
http://www.refg.tu-sofia.bg/JavaBg Java.html
http://yahoo.com yahoo.html
import java.util.Vector;
import java.io.*; import java.net.*; public class WebFetchApp { public static void main(String args[]){ WebFetch fetch = new WebFetch(); fetch.run(); } } class WebFetch { String urlList = "url-list.txt"; Vector URLs = new Vector(); Vector fileNames = new Vector(); public void getURLList() { try { BufferedReader inStream = new BufferedReader(new FileReader(urlList)); String inLine; while((inLine = inStream.readLine()) != null) { inLine = inLine.trim(); if(!inLine.equals("")) { int tabPos = inLine.lastIndexOf('\t'); String url = inLine.substring(0,tabPos).trim(); String fileName = inLine.substring(tabPos+1).trim(); URLs.addElement(url); fileNames.addElement(fileName); } } } catch(IOException ex){ error("Error reading "+urlList); } } |
public void run() {
getURLList(); int numURLs = URLs.size(); for(int i=0;i<numURLs;++i) fetchURL((String) URLs.elementAt(i),(String) fileNames.elementAt(i)); System.out.println("Done."); } public void fetchURL(String urlName,String fileName) { try{ URL url = new URL(urlName); System.out.println("Getting "+urlName+"..."); File outFile = new File(fileName); PrintWriter outStream = new PrintWriter(new FileWriter(outFile)); BufferedReader inStream = new BufferedReader( new InputStreamReader(url.openStream())); String line; while ((line = inStream.readLine())!= null) outStream.println(line); inStream.close(); outStream.close(); }catch (MalformedURLException ex){ System.out.println("Bad URL"); }catch (IOException ex){ System.out.println("IOException occurred."); } } public void error(String s){ System.out.println(s); System.exit(1); } } |