Java初级笔记No.10之Java程序实例(集合&网络实例)

I、集合

1.1 数组转化为集合

使用java Util类的Array.asList(name)方法将数组转化为集合:

package collections;

import java.util.*;
import java.io.*;

public class Array2CollectionEmp {
    public static void main(String args[]) throws IOException {
        int n = 5;
        String[] name = new String[n];
        for (int i = 0; i < n; i++) {
            name[i] = String.valueOf(i);
        }
        
        List<String> list = Arrays.asList(name);
        //System.out.println();
        
        for (String li : list) {
            String str = li;
            System.out.print(str + " ");
        }
    }
}

1.2 集合比较

将字符串转换为集合并使用Collection类的Collection.min()Collection.max()来比较集合中的元素:

package collections;

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

public class CompareCollectionEmp {
    public static void main(String[] args) {
        String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };
        Set<String> set = new TreeSet<String>();
        for (int i = 0; i < coins.length; i++) {
            set.add(coins[i]);
        }
        
        System.out.println(Collections.min(set));
        System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
        for (int i = 0; i <= 10; i++) {
            System.out.print("-");
        }
        
        System.out.println("");
        System.out.println(Collections.max(set));
        System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER));
    }
}

1.3 HashMap遍历

使用Collection类的iterator()方法来遍历集合:

package collections;

import java.util.*;

public class HashMapIterEmp {
    public static void main(String[] args) {
        HashMap<String, String> hMap = new HashMap<String, String>();
        hMap.put("1", "1st");
        hMap.put("2", "2nd");
        hMap.put("3", "3rd");
        
        Collection cl = hMap.values();
        Iterator itr = cl.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

1.4 集合长度

使用Collections类的collection.add()来添加数据,并使用collection.size()来计算集合的长度:

package collections;

import java.util.*;

public class CollectionSizeEmp {
    public static void main(String[] args) {
        int size;
        HashSet collection = new HashSet();
        String str1 = "Yellow", str2 = "White",
                str3 = "Green", str4 = "Blue";
        
        Iterator iterator;
        collection.add(str1);
        collection.add(str2);
        collection.add(str3);
        collection.add(str4);
        
        System.out.print("集合数据:");
        iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
        
        size = collection.size();
        if (collection.isEmpty()) {
            System.out.println("collection is empty!");
        }
        
        else {
            System.out.print("collection's size is " + size + "\n");
        }
    }
}
1.5 HashMap遍历

使用Collection类的iterator()方法来遍历集合:

package collections;

import java.util.*;

public class HashMapIteratorEmp {
    public static void main(String[] args) {
        HashMap<String, String> hMap = new HashMap<String, String>();
        
        hMap.put("1", "1st");
        hMap.put("2", "2nd");
        hMap.put("3", "3rd");
        Collection cl = hMap.values();
        Iterator itr = cl.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

1.6 集合反转

使用Collection和Listiterator类的listIterator()collection.reverse()方法来反转集合中的元素:

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

public class CollectionReverseEmp {
    public static void main(String[] args){
        String[] coins = { "A", "B", "C", "D", "E" };
        List l = new ArrayList();
        for (int i = 0; i < coins.length; i++) {
            l.add(coins[i]);
        }
        ListIterator liter = l.listIterator();
        System.out.println("before reverse:");
        while (liter.hasNext()) {
            System.out.println(liter.next());
        }
        
        Collections.reverse(l);
        liter = l.listIterator();
        System.out.println("after reverse:");
        while (liter.hasNext()) {
            System.out.println(liter.next());
        }
    }
}
1.7 删除集合中指定元素

使用Collection类的collection.remove()方法来删除集合中的指定元素:

package collections;
import java.util.*;

public class CollectionRemoveEmp {
    public static void main(String[] args) {
        int size;
        HashSet collection = new HashSet();
        String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
        Iterator iterator;
        collection.add(str1);
        collection.add(str2);
        collection.add(str3);
        collection.add(str4);
        
        System.out.println("before remove:"); 
        
        iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        
        System.out.println();
        collection.remove(str2);
        System.out.println("after remove:");
        
        iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

1.8 只读集合

使用Collection类的Collections.unmodifiableList()方法来设置集合为只读:

package collections;
import java.util.*;
public class UnmodifiableListEmp {
    public static void main(String[] args) throws Exception{
        List stuff = Arrays.asList(new String[] {"a","b"});
        List list = new ArrayList(stuff);
        list = Collections.unmodifiableList(list);
        
        try {
            list.set(0, "new value");
        } catch (UnsupportedOperationException e) {
            System.out.println("为只读");
        }
        
    }
}

1.9 集合输出

使用java Util 类的keySet()values()firstKey()方法将集合元素输出:

package collections;
import java.util.*;
public class CollectionOutputEmp {
    public static void main(String[] args) {
        TreeMap tMap= new TreeMap();
        tMap.put(1, "Sunday");
        tMap.put(2, "Monday");
        tMap.put(3, "Tuesday");
        tMap.put(4, "Wednesday");
        tMap.put(5, "Thursday");
        tMap.put(6, "Friday");
        tMap.put(7, "Saturday");
        
        System.out.println("keys of TreeMap: " + tMap.keySet());
        
        System.out.println("values of TreeMap: " + tMap.values());
        
        System.out.println("key is 5 :" + tMap.get(5));
        
        System.out.println("the first key: " + tMap.firstKey());
        
        System.out.println("the last key: " + tMap.lastKey());
        
        System.out.println("remove the last key: " + tMap.remove(tMap.lastKey()));
        
        System.out.println("now, keys of TreeMap: " + tMap.keySet());
        
        System.out.println("now, values of TreeMap: " + tMap.values());
    }
}

1.10 List循环移动元素

使用Collections类的rotate()来循环移动元素,其中第二个参数指定了移动的起始位置:

package collections;
import java.util.*;
public class RotateEmp {
    public static void main(String[] args) {
        List list = Arrays.asList("one two three four five size".split(" "));
        System.out.println("The List is :" + list);
        Collections.rotate(list, 3);
        System.out.println("rotate: " + list);
    }
}

1.11 遍历HashTable的键值
package collections;
import java.util.Enumeration;
import java.util.Hashtable;
public class EnumerationEmp {
    public static void main(String[] args) {
        Hashtable ht = new Hashtable();
        ht.put("1", "One");
        ht.put("2", "Two");
        ht.put("3", "Three");
        
        Enumeration e = ht.keys();
        while (e.hasMoreElements()) {
            System.out.println(e.nextElement());
        }
    }
}

1.12 List元素替换

使用Collections类的replaceAll()方法替换List中的所有指定元素:

package collections;
import java.util.*;
public class ReplaceAllEmp {
    public static void main(String[] args) {
        List list = Arrays.asList("one two three four five six one three Four".split(" "));
        System.out.println("The list is : " + list);
        Collections.replaceAll(list, "one", "One");
        System.out.println("after replace : " + list);
    }
}

1.13 List 截取

使用Collections类的indexOfSubList()lastIndexOfSubList()方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置:

package collections;
import java.util.*;
public class ListSubListEmp {
    public static void main(String[] args) {
        List list = Arrays.asList("one two three four five six one three four".split(" "));
        System.out.println("List is : " + list);
        List sublist = Arrays.asList("three four".split(" "));
        
        System.out.println("sublist is : " + sublist);
        
        System.out.println("indexOfSubList: " + Collections.indexOfSubList(list, sublist));
        
        System.out.println("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist));
    }
}

II、网络实例

2.1 查看指定主机的IP地址

使用InetAddress类的InetAddress.getByName()方法来获取指定主机的IP地址:

package net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddressEmp {
    public static void main(String[] args) {
        InetAddress address = null;
        try {
            address = InetAddress.getByName("www.baidu.com");
        } catch (UnknownHostException e){ 
            System.exit(2);
        }
        
        System.out.println(address.getHostName() + "=" + address.getHostAddress());
        System.exit(0);
    }
    
}

2.2 查看端口是否使用
package net;
import java.net.*;
import java.io.*;
public class PostEmp {
    public static void main(String[] args) {
        Socket Skt;
        String host = "localhost";
        if (args.length > 0) {
           host = args[0];
        }
        for (int i = 0; i < 1024; i++) {
           try {
              System.out.println("查看 "+ i);
              Skt = new Socket(host, i);
              System.out.println("端口 " + i + " 已被使用");
           }
           catch (UnknownHostException e) {
              System.out.println("Exception occured"+ e);
              break;
           }
           catch (IOException e) {
           }
        }
     }
}

2.3 获取本机ip地址及主机名

使用InetAddress类的getLocalAddress()方法获取本机ip地址及主机名:

package net;
import java.net.InetAddress;
public class GetLocalAddressEmp {
    public static void main(String[] args) throws Exception{
        InetAddress addr = InetAddress.getLocalHost();
        System.out.println("Local HostAddress: " + addr.getHostAddress());
        
        System.out.println("Local host name: " + addr.getHostName());
    }
}

2.4 获取远程文件大小
package net;
import java.net.URL;
import java.net.URLConnection;
public class FileSizeEmp {
    public static void main(String[] args) throws Exception {
        int size;
        URL url = new URL("https://upload-images.jianshu.io/upload_images/10118224-762b98d6db641801.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/669/format/webp");
        URLConnection conn = url.openConnection();
        size = conn.getContentLength();
        if (size < 0)
            System.out.println("cannot get the size");
        else 
            System.out.println("the size is : " + size + " bytes");
        
        conn.getInputStream().close();
    }
}

2.5 Socket实现多线程服务器程序

使用Socket类的accept()方法和ServerSocket类的MultiThreadServer(socketname)方法来实现多线程服务器程序:

package net;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThreadServerEmp implements Runnable {
    Socket csocket;
    MultiThreadServerEmp(Socket csocket) {
        this.csocket = csocket;
    }
    
    public static void main(String[] args) throws Exception {
        ServerSocket ssock = new ServerSocket(1234);
        System.out.println("Listening");
        while (true) {
            Socket sock = ssock.accept();
            System.out.println("Connected");
            new Thread(new MultiThreadServerEmp(sock)).start();
        }
    }
    
    public void run() {
        try {
            PrintStream pstream = new PrintStream(csocket.getOutputStream());
            for (int i = 100; i >= 0; i--) {
                pstream.println(i + "bottles of beer on the wall");
            }
            
            pstream.close();
            csocket.close();
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
    
}

使用实现Runnable接口的方式来实现线程,需要重写run方法。

2.6 使用Socket连接到指定主机

使用net.Socket类的getInetAddress()方法来连接到指定主机(类似于ping):

package net;
import java.net.InetAddress;
import java.net.Socket;
public class WebPingEmp {
    public static void main(String[] args) {
        try {
            InetAddress addr;
            Socket sock = new Socket("www.baidu.com", 80);
            addr = sock.getInetAddress();
            System.out.println("connected " + addr);
            sock.close();
        }
        catch (java.io.IOException e) {
            System.out.println("cannot connect " + args[0]);
            System.out.println(e);
        }
    }
}

2.7 获取URL相应头的日期信息

使用HttpURLConnection 的 httpCon.getDate()方法来获取URL响应头的日期信息:

package net;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
public class URLGetDateEmp {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.baidu.com");
        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
        long date = httpCon.getDate();
        
        if (date == 0) {
            System.out.println("cannot get date");
        }
        else {
            System.out.println("the date is : " + new Date(date));
        }
    }
}

2.8 获取URL响应头信息
package net;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;

public class URLGetHeaderEmp {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://www.baidu.com");
        URLConnection conn = url.openConnection();
        
        Map headers = conn.getHeaderFields();
        Set<String> keys = headers.keySet();
        
        for (String key : keys) {
            String val = conn.getHeaderField(key);
            System.out.println(key + " " + val);
        }
        System.out.println(conn.getLastModified());  //最后一次修改日期
    }
}

2.9 解析URL

使用URL类的getProtocol()getFile()等方法解析URL地址:

package net;
import java.net.URL;
public class URLProcessEmp {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.baidu.com");
        System.out.println("URL is " + url.toString());
        System.out.println("Protocol " + url.getProtocol());
        System.out.println("File " + url.getFile());
        System.out.println("Host " + url.getHost());
        System.out.println("Path " + url.getPath());
        System.out.println("Port " + url.getPort());
        
        System.out.println("Default Port " + url.getDefaultPort());
    }
}

2.10 ServerSocket与Socket通信

建立服务器端:
· 服务器建立通信ServerSocket;
· 服务端建立Socket接受客户端连接;
· 建立IO输入流读取客户端发送的数据;
· 建立IO输出流向客户端发送数据消息;

package net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerEmp {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8888);
            System.out.println("start server...");
            Socket s = ss.accept();
            System.out.println("client:" + s.getInetAddress().getLocalHost() + "has connected the server");
            
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            
            String mess = br.readLine();
            System.out.println("client: " + mess);
            
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            
            bw.write(mess + "\n");
            bw.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

建立客户端:

· 创建Socket通信,设置通信服务器的IP和Port;
· 建立IO输出流向服务器发送数据消息;
· 建立IO输入流读取服务器发送来的数据消息;

package net;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientEmp {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("127.0.0.1", 8888);
            
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();
            
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            
            //向服务器端发送一条消息
            bw.write("测试客户端和服务端通信,服务器收到后返回到客户端\n");
            bw.flush();
            
            //读取服务器返回的消息
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String mess = br.readLine();
            System.out.println("server: " + mess);  
            
        }
        catch (UnknownHostException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,580评论 18 139
  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 2,362评论 0 4
  • 查看笔记 很多新用户在刚使用的时候,总是将复习计划和复习笔记弄混。我在这里重新强调一下,出现在首页的都是当天的复习...
    艾宾浩斯复习笔记阅读 3,696评论 1 10
  • 2018年1月28日 星期日 天气: 多云 潘紫涵妈妈亲子日记 昨天下午带孩子来到青岛,今天早上到儿童医院...
    潘紫涵妈妈阅读 118评论 0 2
  • 舟横几度涟漪泛, 枯木逢春绿盎然。 斜照余晖增暖色, 浮萍逐水向阳天。
    荔枝_林阅读 155评论 1 1