集册 Java实例教程 解析空格分隔的地址[:port]字符串和InetSocketAddress的返回数组。

解析空格分隔的地址[:port]字符串和InetSocketAddress的返回数组。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

467
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
解析空格分隔的地址[:port]字符串和InetSocketAddress的返回数组。

/*

 * Copyright (c) 2004 by Cosylab

 *

 * The full license specifying the redistribution, modification, usage and other

 * rights and obligations is included with the distribution of this project in

 * the file "LICENSE-CAJ". If the license is not included visit Cosylab web site,

 * <http://www.cosylab.com>.

 *

 * THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, NOT EVEN THE

 * IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE, ASSUMES

 * _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE RESULTING FROM THE USE, MODIFICATION,

 * OR REDISTRIBUTION OF THIS SOFTWARE.

 */

//package com.nowjava;//来自 NowJava.com - 时  代  Java


import java.net.InetSocketAddress;


import java.util.ArrayList;

import java.util.StringTokenizer;


public class Main {

    public static void main(String[] argv) throws Exception {

        String list = "nowjava.com";

        int defaultPort = 2;

        System.out.println(java.util.Arrays.toString(getSocketAddressList(

                list, defaultPort)));

    }


    /**

     * Parse space delimited address[:port] string and return array of <code>InetSocketAddress</code>.  

     * @param list   space delimited address[:port] string.

     * @param defaultPort   port take if not specified.

     * @return   array of <code>InetSocketAddress</code>.

     */

    public static InetSocketAddress[] getSocketAddressList(String list,

            int defaultPort) {

        return getSocketAddressList(list, defaultPort, null);

    }
    /*
     from 时代Java - N o w  J a v a . c o m 
    */


    /**

     * Parse space delimited address[:port] string and return array of <code>InetSocketAddress</code>.  

     * @param list   space delimited address[:port] string.

     * @param defaultPort   port take if not specified.

     * @param appendList    list to be appended.

     * @return   array of <code>InetSocketAddress</code>.

     */

    public static InetSocketAddress[] getSocketAddressList(String list,

            int defaultPort, InetSocketAddress[] appendList) {

        ArrayList al = new ArrayList();


        // parse string

        StringTokenizer st = new StringTokenizer(list);

        while (st.hasMoreTokens()) {

            int port = defaultPort;

            String address = st.nextToken();


            // check port

            int pos = address.indexOf(':');

            if (pos >= 0) {

                try {

                    port = Integer.parseInt(address.substring(pos + 1));

                } catch (NumberFormatException nfe) { /* noop */

                }


                address = address.substring(0, pos);

            }


      
展开阅读全文