Java程式開啟指定地址網頁

來源:互聯網
上載者:User

標籤:技術分享   dll   while   tabs   pip   add   linux   prot   string   

1、今天遇到了需要手動輸入http地址開啟指定網頁的需求,試著做一個用程式開啟指定網頁的功能,搜了一下,還真有一個現成的例子,稍加改造,實現自己的需求;

2、代碼不多,兩個檔案;如下:

package com.lgp.solr;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class JavaFile {        public static List<String> getUrl(String path) {        List<String> urls = new ArrayList<String>();        try {            FileReader reader = new FileReader(path);            BufferedReader br = new BufferedReader(reader);            String str = null;            while ((str = br.readLine()) != null) {                if(str!=null  && str.startsWith("http")){                    urls.add(str);                }            }            br.close();            reader.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return urls;    }}

這個類主要作用是讀取指定檔案的中的url地址,按行讀取,過濾以http開頭的行內容;

package com.lgp.solr;///////////////////////////////////////////////////////////Bare Bones Browser Launch                            ////Version 1.5 (December 10, 2005)                    ////By Dem Pilafian                                                ////支援: Mac OS X, GNU/Linux, Unix, Windows XP////可免費使用                                                        ///////////////////////////////////////////////////////////import java.io.File;/** * @author Dem Pilafian * @author John Kristian */import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;public class BareBonesBrowserLaunch {        public static void main(String[] args) {                String path = System.getProperty("app.home");                if(path==null || "".equals(path)){            path = System.getProperty("file.path");            if(path==null || "".equals(path))                throw new RuntimeException("未配置app.home和file.path");        }        List<String> urls =  new ArrayList<String>();                if(new File(path).isDirectory()){            File dir = new File(path);            for (File file : dir.listFiles()) {                urls.addAll(JavaFile.getUrl(file.getAbsolutePath()));            }        }else{            urls.addAll(JavaFile.getUrl(path));        }                for (String url : urls) {            openURL(url);        }            }        public static void openURL(String url) {        try {            browse(url);        } catch (Exception e) {        }    }    @SuppressWarnings({ "rawtypes", "unchecked" })    private static void browse(String url) throws Exception {        //擷取作業系統的名字        String osName = System.getProperty("os.name", "");        if (osName.startsWith("Mac OS")) {            //蘋果的開啟檔案            Class fileMgr = Class.forName("com.apple.eio.FileManager");            Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });            openURL.invoke(null, new Object[] { url });        } else if (osName.startsWith("Windows")) {           //windows的開啟檔案。            /*String browspath = System.getProperty("brows.path");            try {                if(browspath != null){                    Runtime.getRuntime().exec("browspath " + url);                }                //Runtime.getRuntime().exec("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe " + url);            } catch (Exception e) {                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);            }            */            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);                    } else {            // Unix or Linux的開啟檔案            String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };            String browser = null;            for (int count = 0; count < browsers.length && browser == null; count++)                //執行代碼,在brower有值後跳出,                //這裡是如果進程建立成功了,==0是表示正常結束。                if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)                    browser = browsers[count];            if (browser == null)                throw new Exception("Could not find web browser");            else                //這個值在上面已經成功的得到了一個進程。                Runtime.getRuntime().exec(new String[] { browser, url });        }    }}

這是主類,適用於mac和Linux,mac系統,很強大;其中主要使用windows系統,開啟預設瀏覽器;

3、打成可執行檔jar包:注意設定main方法的路徑,

      

從圖1一路Next,設定jar包路徑後,之後再繼續設定圖2,最後Finish;

4、通過bat檔案運行jar:

run.bat檔案:當讓前提是設定了javahome和classpath等;

set dir=%CD%java -Dapp.home=%CD%\config -jar %CD%\auto.jar

在jar的所在路徑建立config檔案夾,所以設定檔放到此檔案夾內,點擊run.bat測試回合結果。

 

Java程式開啟指定地址網頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.