Java网络编程--简易下载器实现

来源:互联网 发布:js打开微信浏览器 编辑:程序博客网 时间:2024/05/08 00:36
package study;import java.io.*;import java.net.*;public class Main {static String source = "http://down.daomuxiaoshuo.com/down/201304/gcd.txt";String fileName = null;URL url = null;InputStream in = null;static File file = null;DataOutputStream dos = null;URLConnection con = null;// 连接public void connection() {try {url = new URL(source);} catch (MalformedURLException e) {e.printStackTrace();}try {con = url.openConnection();} catch (IOException e) {e.printStackTrace();}}// 创建本地文件public void createFile() {file = new File(fileName);if (!file.exists()) {try {file.createNewFile();} catch (IOException e) {e.printStackTrace();}}}//将从网络获取的文件的InputStream并写入到本地private void writeResult(){FileOutputStream fos = null;try{fos = new FileOutputStream(file,true);}catch(FileNotFoundException e){e.printStackTrace();}BufferedOutputStream bos = new BufferedOutputStream(fos);dos = new DataOutputStream(bos);  try{in = con.getInputStream();}catch(IOException e){e.printStackTrace();}BufferedInputStream bis = new BufferedInputStream(in);DataInputStream dis = new DataInputStream(bis);try{while(true){dos.write(dis.readByte());}}catch(EOFException e){System.out.println("DownLoad!");}catch(IOException e){e.printStackTrace();}try{dos.close();bis.close();}catch(IOException e){e.printStackTrace();}}public void setFileName(String sourceUrl){fileName = sourceUrl.substring(sourceUrl.lastIndexOf("/")+1,sourceUrl.length()).trim();}public static void main(String[] args) {Main main = new Main();main.setFileName(source);main.connection();main.createFile();main.writeResult();}}

0 0
原创粉丝点击