java 下載歷程

做了一個社團分配的任務,還算不錯,能夠部分實現了它的功能了,但主要的界面設計。。。哎,頭疼,算啦,慢慢來吧,總會把他搞定的!!


部分代碼(無界面,但實現了下載功能):

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URISyntaxException;

import java.net.URL;

import java.net.URLConnection;

import java.util.Scanner;

//import java.awt.Desktop;

public class test_url {

private static URL url;

//URL u=this.getDocumentBase();

public static void main(String args[])throws IOException, URISyntaxException{

test_url s=new test_url();

Scanner sc =new Scanner(System.in);

System.out.println("請輸入網址:");

String s2=sc.next();

String url="http://"+s2;

try {

URL U=new URL(url);

URLConnection c=U.openConnection();

InputStream file=c.getInputStream();

String fname = U.getFile().substring(U.getFile().lastIndexOf("/") + 1);

String xxx=fname.substring(fname .lastIndexOf(".")+1);

System.out.println("輸入文件名:");

String s1=sc.next();

FileOutputStream out=new FileOutputStream("G:/"+s1+"."+xxx);

System.out.println("開始下載");

int k;

while((k=file.read())>=0){

         run(k);

out.write(k);

out.flush();

}

out.close();

file.close();

System.out.println("下載完成");

 

//java.awt.Desktop.getDesktop().browse(new URL(url).toURI());

/*HttpURLConnection h=(HttpURLConnection)(U.openConnection());

int num=h.getResponseCode();

if(num>400){

System.out.println("錯誤!");

}*/

//new URL(url).toURI();

} catch (MalformedURLException e) {

e.printStackTrace();

}

/*File f=new File(s);

FileInputStream file=new FileInputStream(f);

FileOutputStream file2=new FileOutputStream("G:/");

int num;

while((num=file.read())!=-1){

file2.write(num);

}

System.out.println("文件保存成功!");*/

}

 

public static void run(int m) {

try{

while(m>=0){

Thread.sleep(1000);

}

}catch(Exception e){

e.printStackTrace();

}

run(m);

}

}

發佈了15 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章