java菜鸟教程学习(完整版)

java实例

  • 一.Java 字符串
  • 1.Java 实例 – 字符串比较
  • 2.Java 实例 – 查找字符串最后一次出现的位置
  • 3.Java 实例 – 删除字符串中的一个字符
  • 4.Java 实例 – 字符串替换
  • 5.Java 实例 – 字符串反转
  • 6.Java 实例 – 字符串查找
  • 7.Java 实例 – 字符串分割
  • 8.Java 实例 – 字符串分割(StringTokenizer)
  • 9.Java 实例 – 字符串小写转大写
  • 10.Java 实例 – 测试两个字符串区域是否相等
  • 11.Java 实例 – 字符串性能比较测试
  • 12.Java 实例 – 字符串优化
  • 13.Java 实例 – 字符串格式化
  • 14.Java 实例 – 连接字符串
  • 二.Java 数组
  • 1.Java 实例 – 数组排序及元素查找
  • 2.Java 实例 – 数组添加元素
  • 3.Java 实例 – 获取数组长度
  • 4.Java 实例 – 数组反转
  • 5.Java 实例 – 数组输出
  • 6.Java 实例 – 数组获取最大和最小值
  • 7.Java 实例 – 数组合并
  • 8.Java 实例 – 数组填充
  • 9.Java 实例 – 数组扩容
  • 10.Java 实例 – 查找数组中的重复元素
  • 11.Java 实例 – 删除数组元素
  • 12.Java 实例 – 数组差集
  • 13.Java 实例 – 数组交集
  • 14.Java 实例 – 在数组中查找指定元素
  • 15.Java 实例 – 判断数组是否相等
  • 16.Java 实例 – 数组并集
  • 三.Java 时间处理
  • 1.Java 实例 – 格式化时间(SimpleDateFormat)
  • 2.Java 实例 – 获取当前时间
  • 3.Java 实例 – 获取年份、月份等
  • 4.Java 实例 – 时间戳转换成时间
  • 四.Java 方法
  • 1.Java 实例 – 方法重载
  • 2.Java 实例 – 输出数组元素
  • 3.Java 实例 – 汉诺塔算法
  • 4.Java 实例 – 斐波那契数列
  • 5.Java 实例 – 阶乘
  • 6.Java 实例 – 方法覆盖
  • 7.Java 实例 – instanceOf 关键字用法
  • 8.Java 实例 – break 关键字用法
  • 9.Java 实例 – continue 关键字用法
  • 10.Java 实例 – 标签(Label)
  • 11.Java 实例 – enum 和 switch 语句使用
  • 12.Java 实例 – Enum(枚举)构造函数及方法的使用
  • 13.Java 实例 – for 和 foreach循环使用
  • 14.Java 实例 – Varargs 可变参数使用
  • 15.Java 实例 – 重载(overloading)方法中使用 Varargs
  • 五.打印图形
  • 1.Java 实例 – 打印菱形
  • 2.Java 实例 – 九九乘法表
  • 3.Java 实例 – 打印三角形
  • 4.Java 实例 – 打印倒立的三角形
  • 5.Java 实例 – 打印平行四边形
  • 6.Java 实例 – 打印矩形
  • 六.Java 文件操作
  • 1.Java 实例 – 文件写入
  • 2.Java 实例 – 读取文件内容
  • 3.Java 实例 – 删除文件
  • 4.Java 实例 – 将文件内容复制到另一个文件
  • 5.Java 实例 – 向文件中追加数据
  • 6.Java 实例 – 创建临时文件
  • 7.Java 实例 – 修改文件最后的修改日期
  • 8.Java 实例 – 获取文件大小
  • 9.Java 实例 – 文件重命名
  • 10.Java 实例 – 设置文件只读
  • 11.Java 实例 – 检测文件是否存在
  • 12.Java 实例 – 在指定目录中创建文件
  • 13.Java 实例 – 获取文件修改时间
  • 14.Java 实例 – 创建文件
  • 15.Java 实例 – 文件路径比较
  • 七.Java 目录操作
  • 1.Java 实例 – 递归创建目录
  • 2.Java 实例 – 删除目录
  • 3.Java 实例 – 判断目录是否为空
  • 4.Java 实例 – 判断文件是否隐藏
  • 5.Java 实例 – 获取目录大小
  • 6.Java 实例 – 在指定目录中查找文件
  • 7.Java 实例 – 获取文件的上级目录
  • 8.Java 实例 – 获取目录最后修改时间
  • 9.Java 实例 – 打印目录结构
  • 10.Java 实例 – 遍历指定目录下的所有目录
  • 11.Java 实例 – 遍历指定目录下的所有文件
  • 12.Java 实例 – 在指定目录中查找文件
  • 13.Java 实例 – 遍历系统根目录
  • 14.Java 实例 – 查看当前工作目录
  • 15.Java 实例 – 遍历目录
  • 八.Java 异常处理
  • 1.Java 实例 – 异常处理方法
  • 2.Java 实例 – 多个异常处理(多个catch)
  • 3.Java 实例 – Finally的用法
  • 4.Java 实例 – 使用 catch 处理异常
  • 5.Java 实例 – 多线程异常处理
  • 6.Java 实例 – 获取异常的堆栈信息
  • 7.Java 实例 – 重载方法异常处理
  • 8.Java 实例 – 链试异常
  • 9.Java 实例 – 自定义异常
  • 九.Java 数据结构
  • 1.Java 实例 – 数字求和运算
  • 2.Java 实例 – 利用堆栈将中缀表达式转换成后缀
  • 3.Java 实例 – 在链表(LinkedList)的开头和结尾
  • 4.Java 实例 – 获取链表(LinkedList)的第一个
  • 5.Java 实例 – 删除链表中的元素
  • 6.Java 实例 – 获取链表的元素
  • 7.Java 实例 – 获取向量元素的索引值
  • 8.Java 实例 – 栈的实现
  • 9.Java 实例 – 链表元素查找
  • 10.Java 实例 – 压栈出栈的方法实现字符串反转
  • 11.Java 实例 – 队列(Queue)用法
  • 12.Java 实例 – 获取向量的最大元素
  • 13.Java 实例 – 链表修改
  • 14.Java 实例 – 旋转向量
  • 十.Java 集合
  • 1.Java 实例 – 数组转集合
  • 2.Java 实例 – 集合比较
  • 3.Java 实例 – HashMap遍历
  • 4.Java 实例 – 集合长度
  • 5.Java 实例 – 集合打乱顺序
  • 6.Java 实例 – 集合遍历
  • 7.Java 实例 – 集合反转
  • 8.Java 实例 – 删除集合中指定元素
  • 9.Java 实例 – 只读集合
  • 10.Java 实例 – 集合输出
  • 11.Java 实例 – 集合转数组
  • 12.Java 实例 – List 循环移动元素
  • 13.Java 实例 – 查找 List 中的最大最小值
  • 14.Java 实例 – 遍历 HashTable 的键值
  • 15.Java 实例 – 使用 Enumeration 遍历 HashTable
  • 16.Java 实例 – 集合中添加不同类型元素
  • 17.Java 实例 – List 元素替换
  • 18.Java 实例 – List 截取
  • 十一.Java 网络实例
  • 1.Java 实例 – 获取指定主机的IP地址
  • 2.Java 实例 – 查看端口是否已使用
  • 3.Java 实例 – 获取本机ip地址及主机名
  • 4.Java 实例 – 获取远程文件大小
  • 5.Java 实例 – Socket 实现多线程服务器程序
  • 6.Java 实例 – 查看主机指定文件的最后修改时间
  • 7.Java 实例 – 使用 Socket 连接到指定主机
  • 8.Java 实例 – 网页抓取
  • 9.Java 实例 – 获取 URL响应头的日期信息
  • 10.Java 实例 – 获取 URL 响应头信息
  • 11.Java 实例 – 解析 URL
  • 12.Java 实例 – ServerSocket 和 Socket 通信实例
  • 十二.Java 线程
  • 1.Java 实例 – 查看线程是否存活
  • 2.Java 实例 – 获取当前线程名称
  • 3.Java 实例 – 状态监测
  • 4.Java 实例 – 线程优先级设置
  • 5.Java 实例 – 死锁及解决方法
  • 6.Java 实例 – 获取线程id
  • 7.Java 实例 – 线程挂起
  • 8.Java 实例 – 终止线程
  • 9.Java 实例 – 生产者/消费者问题
  • 10.Java 实例 – 获取线程状态
  • 11.Java 实例 – 获取所有线程
  • 12.Java 实例 – 查看线程优先级
  • 13.Java 实例 – 中断线程
  • 一.Java 字符串

    1.Java 实例 – 字符串比较

    public class StringCompareEmp{
       public static void main(String args[]){
          String str = "Hello World";
          String anotherString = "hello world";
          Object objStr = str;
     
          System.out.println( str.compareTo(anotherString) );
          System.out.println( str.compareToIgnoreCase(anotherString) );  //忽略大小写
          System.out.println( str.compareTo(objStr.toString()));
       }
    }
    

    2.Java 实例 – 查找字符串最后一次出现的位置

    public class SearchlastString {
       public static void main(String[] args) {
          String strOrig = "Hello world ,Hello Runoob";
          int lastIndex = strOrig.lastIndexOf("Runoob");
          if(lastIndex == - 1){
             System.out.println("没有找到字符串 Runoob");
          }else{
             System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex);
          }
       }
    }
    

    3.Java 实例 – 删除字符串中的一个字符

    public class Main {
       public static void main(String args[]) {
          String str = "this is Java";
          System.out.println(removeCharAt(str, 3));
       }
       public static String removeCharAt(String s, int pos) {
          return s.substring(0, pos) + s.substring(pos + 1);
       }
    }
    

    4.Java 实例 – 字符串替换

    public class StringReplaceEmp{
       public static void main(String args[]){
          String str="Hello World";
          System.out.println( str.replace( 'H','W' ) );
          System.out.println( str.replaceFirst("He", "Wa") );
          System.out.println( str.replaceAll("He", "Ha") );
       }
    }
    

    5.Java 实例 – 字符串反转

    public class StringReverseExample{
       public static void main(String[] args){
          String string="runoob";
          String reverse = new StringBuffer(string).reverse().toString();
          System.out.println("字符串反转前:"+string);
          System.out.println("字符串反转后:"+reverse);
       }
    }
    

    6.Java 实例 – 字符串查找

    public class SearchStringEmp {
       public static void main(String[] args) {
          String strOrig = "Google Runoob Taobao";
          int intIndex = strOrig.indexOf("Runoob");
          if(intIndex == - 1){
             System.out.println("没有找到字符串 Runoob");
          }else{
             System.out.println("Runoob 字符串位置 " + intIndex);
          }
       }
    }
    

    7.Java 实例 – 字符串分割

    public class JavaStringSplitEmp {
       public static void main(String args[]){
          
          String str = "www-runoob-com";
          String[] temp;
          String delimeter = "-";  // 指定分割字符
          temp = str.split(delimeter); // 分割字符串
          // 普通 for 循环
          for(int i =0; i < temp.length ; i++){
             System.out.println(temp[i]);
             System.out.println("");
          }
     
          System.out.println("------java for each循环输出的方法-----");
          String str1 = "www.runoob.com";
          String[] temp1;
          String delimeter1 = "\\.";  // 指定分割字符, . 号需要转义
          temp1 = str1.split(delimeter1); // 分割字符串
          for(String x :  temp1){
             System.out.println(x);
             System.out.println("");
          }
       }
    }
    

    8.Java 实例 – 字符串分割(StringTokenizer)

    import java.util.StringTokenizer;
     
    public class Main {
        public static void main(String[] args) {
     
            String str = "This is String , split by StringTokenizer, created by runoob";
            StringTokenizer st = new StringTokenizer(str);
     
            System.out.println("----- 通过空格分隔 ------");
            while (st.hasMoreElements()) {
                System.out.println(st.nextElement());
            }
     
            System.out.println("----- 通过逗号分隔 ------");
            StringTokenizer st2 = new StringTokenizer(str, ",");
     
            while (st2.hasMoreElements()) {
                System.out.println(st2.nextElement());
            }
        }
    }
    

    9.Java 实例 – 字符串小写转大写

    public class StringToUpperCaseEmp {
        public static void main(String[] args) {
            String str = "string runoob";
            String strUpper = str.toUpperCase();
            System.out.println("原始字符串: " + str);
            System.out.println("转换为大写: " + strUpper);
        }
    }
    

    10.Java 实例 – 测试两个字符串区域是否相等

    public class StringRegionMatch{
       public static void main(String[] args){
          String first_str = "Welcome to Microsoft";
          String second_str = "I work with microsoft";
          boolean match1 = first_str.
          regionMatches(11, second_str, 12, 9);
          boolean match2 = first_str.
          regionMatches(true, 11, second_str, 12, 9); //第一个参数 true 表示忽略大小写区别
          System.out.println("区分大小写返回值:" + match1);
          System.out.println("不区分大小写返回值:" + match2);
       }
    }
    

    11.Java 实例 – 字符串性能比较测试

    public class StringComparePerformance{
       public static void main(String[] args){      
          long startTime = System.currentTimeMillis();
          for(int i=0;i<50000;i++){
             String s1 = "hello";
             String s2 = "hello"; 
          }
          long endTime = System.currentTimeMillis();
          System.out.println("通过 String 关键词创建字符串" 
          + " : "+ (endTime - startTime) 
          + " 毫秒" );       
          long startTime1 = System.currentTimeMillis();
          for(int i=0;i<50000;i++){
             String s3 = new String("hello");
             String s4 = new String("hello");
          }
          long endTime1 = System.currentTimeMillis();
          System.out.println("通过 String 对象创建字符串" 
          + " : " + (endTime1 - startTime1)
          + " 毫秒");
       }
    }
    

    12.Java 实例 – 字符串优化

    public class StringOptimization {
        public static void main(String[] args){
            String variables[] = new String[50000];      
            for( int i=0;i <50000;i++){
                variables[i] = "s"+i;
            }
            long startTime0 = System.currentTimeMillis();
            for(int i=0;i<50000;i++){
                variables[i] = "hello";
            }
            long endTime0 = System.currentTimeMillis();
            System.out.println("直接使用字符串: "+ (endTime0 - startTime0)  + " ms" );
            long startTime1 = System.currentTimeMillis();
                for(int i=0;i<50000;i++){
                variables[i] = new String("hello");
            }
            long endTime1 = System.currentTimeMillis();
            System.out.println("使用 new 关键字:" + (endTime1 - startTime1) + " ms");
            long startTime2 = System.currentTimeMillis();
            for(int i=0;i<50000;i++){
                variables[i] = new String("hello");
                variables[i] = variables[i].intern();          
            }
            long endTime2 = System.currentTimeMillis();
            System.out.println("使用字符串对象的 intern() 方法: " 
            + (endTime2 - startTime2)
            + " ms");
        }
    }
    

    13.Java 实例 – 字符串格式化

    import java.util.*;
     
    public class StringFormat {
        public static void main(String[] args){
            double e = Math.E;
            System.out.format("%f%n", e);
            System.out.format(Locale.CHINA  , "%-10.4f%n%n", e);  //指定本地为中国(CHINA)
        }
    }
    

    14.Java 实例 – 连接字符串

    public class StringConcatenate {
        public static void main(String[] args){
            long startTime = System.currentTimeMillis();
            for(int i=0;i<5000;i++){
                String result = "This is"
                + "testing the"
                + "difference"+ "between"
                + "String"+ "and"+ "StringBuffer";
            }
            long endTime = System.currentTimeMillis();
            System.out.println("字符串连接" 
            + " - 使用 + 操作符 : " 
            + (endTime - startTime)+ " ms");
            long startTime1 = System.currentTimeMillis();
            for(int i=0;i<5000;i++){
                StringBuffer result = new StringBuffer();
                result.append("This is");
                result.append("testing the");
                result.append("difference");
                result.append("between");
                result.append("String");
                result.append("and");
                result.append("StringBuffer");
            }
            long endTime1 = System.currentTimeMillis();
            System.out.println("字符串连接" 
            + " - 使用 StringBuffer : "
            + (endTime1 - startTime1)+ " ms");
        }
    }
    

    二.Java 数组

    1.Java 实例 – 数组排序及元素查找

    import java.util.Arrays;
     
    public class MainClass {
        public static void main(String args[]) throws Exception {
            int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
            Arrays.sort(array);
            printArray("数组排序结果为", array);
            int index = Arrays.binarySearch(array, 2);
            System.out.println("元素 2  在第 " + index + " 个位置");
        }
        private static void printArray(String message, int array[]) {
            System.out.println(message
            + ": [length: " + array.length + "]");
            for (int i = 0; i < array.length; i++) {
                if(i != 0){
                    System.out.print(", ");
                }
                System.out.print(array[i]);
            }
            System.out.println();
        }
    }
    

    2.Java 实例 – 数组添加元素

    import java.util.Arrays;
     
    public class MainClass {
       public static void main(String args[]) throws Exception {
          int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
          Arrays.sort(array);
          printArray("数组排序", array);
          int index = Arrays.binarySearch(array, 1);
          System.out.println("元素 1 所在位置(负数为不存在):"
          + index);  
          int newIndex = -index - 1;
          array = insertElement(array, 1, newIndex);
          printArray("数组添加元素 1", array);
       }
       private static void printArray(String message, int array[]) {
          System.out.println(message
          + ": [length: " + array.length + "]");
          for (int i = 0; i < array.length; i++) {
             if (i != 0){
                System.out.print(", ");
             }
             System.out.print(array[i]);         
          }
          System.out.println();
       }
       private static int[] insertElement(int original[],
       int element, int index) {
          int length = original.length;
          int destination[] = new int[length + 1];
          System.arraycopy(original, 0, destination, 0, index);
          destination[index] = element;
          System.arraycopy(original, index, destination, index
          + 1, length - index);
          return destination;
       }
    }
    

    3.Java 实例 – 获取数组长度

    public class Main {
       public static void main(String args[]) {
          String[][] data = new String[2][5];
          System.out.println("第一维数组长度: " + data.length);
          System.out.println("第二维数组长度: " + data[0].length);
       }
    }
    

    4.Java 实例 – 数组反转

    public class RunoobTest { 
      
        /* 反转数组*/
        static void reverse(int a[], int n) 
        { 
            int[] b = new int[n]; 
            int j = n; 
            for (int i = 0; i < n; i++) { 
                b[j - 1] = a[i]; 
                j = j - 1; 
            } 
      
            /*输入反转数组*/
            System.out.println("反转后数组是: \n"); 
            for (int k = 0; k < n; k++) { 
                System.out.println(b[k]); 
            } 
        } 
      
        public static void main(String[] args) 
        { 
            int [] arr = {10, 20, 30, 40, 50}; 
            reverse(arr, arr.length); 
        } 
    }
    

    5.Java 实例 – 数组输出

    public class Welcome {
        public static void main(String[] args){
            String[] runoobs = new String[3];
            runoobs[0] = "菜鸟教程";
            runoobs[1] = "菜鸟工具";
            runoobs[2] = "菜鸟笔记";
            for (int i = 0; i < runoobs.length; i++){
                System.out.println(runoobs[i]);
            }
        }
    }
    

    6.Java 实例 – 数组获取最大和最小值

    import java.util.Arrays;
    import java.util.Collections;
     
    public class Main {
        public static void main(String[] args) {
            Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
            int min = (int) Collections.min(Arrays.asList(numbers));
            int max = (int) Collections.max(Arrays.asList(numbers));
            System.out.println("最小值: " + min);
            System.out.println("最大值: " + max);
        }
    }
    

    7.Java 实例 – 数组合并

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
     
    public class Main {
        public static void main(String args[]) {
            String a[] = { "A", "E", "I" };
            String b[] = { "O", "U" };
            List list = new ArrayList(Arrays.asList(a));
            list.addAll(Arrays.asList(b));
            Object[] c = list.toArray();
            System.out.println(Arrays.toString(c));
        }
    }
    

    8.Java 实例 – 数组填充

    import java.util.*;
     
    public class FillTest {
        public static void main(String args[]) {
            int array[] = new int[6];
            Arrays.fill(array, 100);
            for (int i=0, n=array.length; i < n; i++) {
                System.out.println(array[i]);
            }
            System.out.println();
            Arrays.fill(array, 3, 6, 50);
            for (int i=0, n=array.length; i< n; i++) {
                System.out.println(array[i]);
            }
        }
    }
    

    9.Java 实例 – 数组扩容

    public class Main {
        public static void main(String[] args) {
            String[] names = new String[] { "A", "B", "C" };
            String[] extended = new String[5];
            extended[3] = "D";
            extended[4] = "E";
            System.arraycopy(names, 0, extended, 0, names.length);
            for (String str : extended){
                System.out.println(str);
            }
        }
    }
    

    10.Java 实例 – 查找数组中的重复元素

    public class MainClass {
        public static void main(String[] args) 
        {
            int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2, 9, 2};
            findDupicateInArray(my_array);
     
        }
     
        public static void findDupicateInArray(int[] a) {
            int count=0;
            for(int j=0;j<a.length;j++) {
                for(int k =j+1;k<a.length;k++) {
                    if(a[j]==a[k]) {
                        count++;
                    }
                }
                if(count==1)
                   System.out.println( "重复元素 : " +  a[j] );
                count = 0;
            }
        }
    }
    

    11.Java 实例 – 删除数组元素

    import java.util.Arrays;
     
    public class RunoobTest {
     
        public static void main(String[] args) {
            int[] oldarray = new int[] {3, 4, 5, 6, 7};// 原始数组
            int num = 2;   // 删除索引为 2 的元素,即删除第三个元素 5
            int[] newArray = new int[oldarray.length-1];// 新数组,长度为原始数组减去 1
            
            for(int i=0;i<newArray.length; i++) {
                // 判断元素是否越界
                if (num < 0 || num >= oldarray.length) {
                    throw new RuntimeException("元素越界... "); 
                } 
                // 
                if(i<num) {
                    newArray[i] = oldarray[i];
                }
                else {
                    newArray[i] = oldarray[i+1];
                }
            }
            // 打印输出数组内容
            System.out.println(Arrays.toString(oldarray));
            oldarray = newArray;
            System.out.println(Arrays.toString(oldarray));
        }
    }
    

    12.Java 实例 – 数组差集

    import java.util.ArrayList;
     
    public class Main {
        public static void main(String[] args)  {
            ArrayList objArray = new ArrayList();
            ArrayList objArray2 = new ArrayList();
            objArray2.add(0,"common1");
            objArray2.add(1,"common2");
            objArray2.add(2,"notcommon");
            objArray2.add(3,"notcommon1");
            objArray.add(0,"common1");
            objArray.add(1,"common2");
            objArray.add(2,"notcommon2");
            System.out.println("array1 的元素" +objArray);
            System.out.println("array2 的元素" +objArray2);
            objArray.removeAll(objArray2);
            System.out.println("array1 与 array2 数组差集为:"+objArray);
        }
    }
    

    13.Java 实例 – 数组交集

    import java.util.ArrayList;
     
    public class Main {
        public static void main(String[] args)  {
            ArrayList objArray = new ArrayList();
            ArrayList objArray2 = new ArrayList();
            objArray2.add(0,"common1");
            objArray2.add(1,"common2");
            objArray2.add(2,"notcommon");
            objArray2.add(3,"notcommon1");
            objArray.add(0,"common1");
            objArray.add(1,"common2");
            objArray.add(2,"notcommon2");
            System.out.println("array1 数组元素:"+objArray);
            System.out.println("array2 数组元素:"+objArray2);
            objArray.retainAll(objArray2);
            System.out.println("array2 & array1 数组交集为:"+objArray);
        }
    }
    

    14.Java 实例 – 在数组中查找指定元素

    import java.util.ArrayList;
     
    public class Main {
        public static void main(String[] args)  {
            ArrayList<String> objArray = new ArrayList<String>();
            ArrayList<String> objArray2 = new ArrayList<String>();
            objArray2.add(0,"common1");
            objArray2.add(1,"common2");
            objArray2.add(2,"notcommon");
            objArray2.add(3,"notcommon1");
            objArray.add(0,"common1");
            objArray.add(1,"common2");
            System.out.println("objArray 的数组元素:"+objArray);
            System.out.println("objArray2 的数组元素:"+objArray2);
            System.out.println("objArray 是否包含字符串common2? : "
            +objArray.contains("common2"));
            System.out.println("objArray2 是否包含数组 objArray? :"
            +objArray2.contains(objArray) );
        }
    }
    

    15.Java 实例 – 判断数组是否相等

    import java.util.Arrays;
     
    public class Main {
        public static void main(String[] args) throws Exception {
            int[] ary = {1,2,3,4,5,6};
            int[] ary1 = {1,2,3,4,5,6};
            int[] ary2 = {1,2,3,4};
            System.out.println("数组 ary 是否与数组 ary1相等? :"
            +Arrays.equals(ary, ary1));
            System.out.println("数组 ary 是否与数组 ary2相等? :"
            +Arrays.equals(ary, ary2));
        }
    }
    

    16.Java 实例 – 数组并集

    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Set;
     
     
    public class Main {
        public static void main(String[] args) throws Exception {
            String[] arr1 = { "1", "2", "3" };
            String[] arr2 = { "4", "5", "6" };
            String[] result_union = union(arr1, arr2);
            System.out.println("并集的结果如下:");
     
            for (String str : result_union) {
                System.out.println(str);
            }
        }
     
        // 求两个字符串数组的并集,利用set的元素唯一性
        public static String[] union(String[] arr1, String[] arr2) {
            Set<String> set = new HashSet<String>();
     
            for (String str : arr1) {
                set.add(str);
            }
     
            for (String str : arr2) {
                set.add(str);
            }
     
            String[] result = {  };
     
            return set.toArray(result);
        }
    }
    

    三.Java 时间处理

    1.Java 实例 – 格式化时间(SimpleDateFormat)

    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class Main{
        public static void main(String[] args){
            Date date = new Date();
            String strDateFormat = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
            System.out.println(sdf.format(date));
        }
    }
    

    2.Java 实例 – 获取当前时间

    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class Main{
        public static void main(String[] args){
            
            SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间 
            sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记  
            Date date = new Date();// 获取当前时间 
            System.out.println("现在时间:" + sdf.format(date)); // 输出已经格式化的现在时间(24小时制) 
        } 
    }
    

    3.Java 实例 – 获取年份、月份等

    import java.util.Calendar;
     
    public class Main {
        public static void main(String[] args) {
            Calendar cal = Calendar.getInstance();
            int day = cal.get(Calendar.DATE);
            int month = cal.get(Calendar.MONTH) + 1;
            int year = cal.get(Calendar.YEAR);
            int dow = cal.get(Calendar.DAY_OF_WEEK);
            int dom = cal.get(Calendar.DAY_OF_MONTH);
            int doy = cal.get(Calendar.DAY_OF_YEAR);
     
            System.out.println("当期时间: " + cal.getTime());
            System.out.println("日期: " + day);
            System.out.println("月份: " + month);
            System.out.println("年份: " + year);
            System.out.println("一周的第几天: " + dow);  // 星期日为一周的第一天输出为 1,星期一输出为 2,以此类推
            System.out.println("一月中的第几天: " + dom);
            System.out.println("一年的第几天: " + doy);
        }
    }
    

    4.Java 实例 – 时间戳转换成时间

    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class Main{
        public static void main(String[] args){
            Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));      // 时间戳转换成时间
            System.out.println("格式化结果:" + sd);
     
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
            String sd2 = sdf2.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
            System.out.println("格式化结果:" + sd2);
       }
    }
    

    四.Java 方法

    1.Java 实例 – 方法重载

    class MyClass {
        int height;
        MyClass() {
            System.out.println("无参数构造函数");
            height = 4;
        }
        MyClass(int i) {
            System.out.println("房子高度为 " + i + " 米");
            height = i;
        }
        void info() {
            System.out.println("房子高度为 " + height + " 米");
        }
        void info(String s) {
            System.out.println(s + ": 房子高度为 " + height + " 米");
        }
    }
    public class MainClass {
        public static void main(String[] args) {
            MyClass t = new MyClass(3);
            t.info();
            t.info("重载方法");
            //重载构造函数
            new MyClass();
        }
    }
    

    2.Java 实例 – 输出数组元素

    public class MainClass {
        public static void printArray(Integer[] inputArray) {
            for (Integer element : inputArray){
                System.out.printf("%s ", element);
                System.out.println();
            }
        }
        public static void printArray(Double[] inputArray) {
            for (Double element : inputArray){
                System.out.printf("%s ", element);
                System.out.println();
            }
        }
        public static void printArray(Character[] inputArray) {
            for (Character element : inputArray){
                System.out.printf("%s ", element);
                System.out.println();
            }
        }
        public static void main(String args[]) {
            Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
            Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
            Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
            System.out.println("输出整型数组:");
            printArray(integerArray);
            System.out.println("\n输出双精度型数组:");
            printArray(doubleArray);
            System.out.println("\n输出字符型数组:");
            printArray(characterArray);
        }
    }
    

    3.Java 实例 – 汉诺塔算法

    public class MainClass {
        public static void main(String[] args) {
            int nDisks = 3;
            doTowers(nDisks, 'A', 'B', 'C');
        }
        public static void doTowers(int topN, char from, char inter, char to) {
            if (topN == 1){
                System.out.println("Disk 1 from "
                + from + " to " + to);
            }else {
                doTowers(topN - 1, from, to, inter);
                System.out.println("Disk "
                + topN + " from " + from + " to " + to);
                doTowers(topN - 1, inter, from, to);
            }
        }
    }
    

    4.Java 实例 – 斐波那契数列

    public class MainClass {
        public static void main(String[] args) {
            for (int counter = 0; counter <= 10; counter++){
                System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
            }
        }
     
        public static long fibonacci(long number) {
            if ((number == 0) || (number == 1))
                return number;
            else
                return fibonacci(number - 1) + fibonacci(number - 2);
        }
    }
    

    5.Java 实例 – 阶乘

    public class MainClass {
        public static void main(String args[]) {
        for (int counter = 0; counter <= 10; counter++){
            System.out.printf("%d! = %d\n", counter,
            factorial(counter));
        }
        }
        public static long factorial(long number) {
            if (number <= 1)
                return 1;
            else
                return number * factorial(number - 1);
        }
    }
    

    6.Java 实例 – 方法覆盖

    public class Findareas{
        public static void main (String []agrs){
            Figure f= new Figure(10 , 10);
            Rectangle r= new Rectangle(9 , 5);
            Figure figref;
            figref=f;
            System.out.println("Area is :"+figref.area());
            figref=r;
            System.out.println("Area is :"+figref.area());
        }
    }
    class Figure{
        double dim1;
        double dim2;
        Figure(double a , double b) {
            dim1=a;
            dim2=b;
        }
        Double area() {
            System.out.println("Inside area for figure.");
            return(dim1*dim2);
        }
    }
    class Rectangle extends Figure {
        Rectangle(double a, double b) {
            super(a ,b);
        }
        Double area() {
            System.out.println("Inside area for rectangle.");
            return(dim1*dim2);
        }
    }
    

    7.Java 实例 – instanceOf 关键字用法

    /*
     author by runoob.com
     Main.java
     */
    import java.util.ArrayList;
    import java.util.Vector;
     
    public class Main {
     
    public static void main(String[] args) {
       Object testObject = new ArrayList();
          displayObjectClass(testObject);
       }
       public static void displayObjectClass(Object o) {
          if (o instanceof Vector)
          System.out.println("对象是 java.util.Vector 类的实例");
          else if (o instanceof ArrayList)
          System.out.println("对象是 java.util.ArrayList 类的实例");
          else
          System.out.println("对象是 " + o.getClass() + " 类的实例");
       }
    }
    

    8.Java 实例 – break 关键字用法

    public class Main {
        public static void main(String[] args) {
            int[] intary = { 99,12,22,34,45,67,5678,8990 };
            int no = 5678;
            int i = 0;
            boolean found = false;
            for ( ; i < intary.length; i++) {
                if (intary[i] == no) {
                    found = true;
                    break;
                }
            }
            if (found) {
                System.out.println(no + " 元素的索引位置在: " + i);
            } 
            else {
                System.out.println(no + " 元素不在数组中");
            }
        }
    }
    

    9.Java 实例 – continue 关键字用法

    public class Main {
        public static void main(String[] args) {
            StringBuffer searchstr = new StringBuffer("hello how are you. ");
            int length = searchstr.length();
            int count = 0;
            for (int i = 0; i < length; i++) {
                if (searchstr.charAt(i) != 'h')
                continue;
                count++;
                searchstr.setCharAt(i, 'h');
            }
            System.out.println("发现 " + count 
            + " 个 h 字符");
            System.out.println(searchstr);
        }
    }
    

    10.Java 实例 – 标签(Label)

    public class Main {
        public static void main(String[] args) {
            outerLoop:
            for (int i = 0; i < 3; i++) {
                innerLoop:
                for (int j = 0; j < 3; j++) {
                    if (i == 1 && j == 1) {
                        break outerLoop; // 跳出外部循环
                    }
                    System.out.println("i: " + i + ", j: " + j);
                }
            }
        }
    }
    

    11.Java 实例 – enum 和 switch 语句使用

    enum Car {
        lamborghini,tata,audi,fiat,honda
    }
    public class Main {
        public static void main(String args[]){
            Car c;
            c = Car.tata;
            switch(c) {
                case lamborghini:
                    System.out.println("你选择了 lamborghini!");
                    break;
                case tata:
                    System.out.println("你选择了 tata!");
                    break;
                case audi:
                    System.out.println("你选择了 audi!");
                    break;
                case fiat:
                    System.out.println("你选择了 fiat!");
                    break;
                case honda:
                    System.out.println("你选择了 honda!");
                    break;
                default:
                    System.out.println("我不知道你的车型。");
                    break;
            }
        }
    }
    

    12.Java 实例 – Enum(枚举)构造函数及方法的使用

    enum Car {
        lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
        private int price;
        Car(int p) {
            price = p;
        }
        int getPrice() {
            return price;
        } 
    }
    public class Main {
        public static void main(String args[]){
            System.out.println("所有汽车的价格:");
            for (Car c : Car.values())
            System.out.println(c + " 需要 " 
            + c.getPrice() + " 千美元。");
        }
    }
    

    13.Java 实例 – for 和 foreach循环使用

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
     
    public class Main
    {
        public static void main(String[] args)
        {
            int[] arr = {1, 2, 3, 4, 5};
            
            System.out.println("----------使用 for 循环------------");
            for(int i=0; i<arr.length; i++)
            {
                System.out.println(arr[i]);
            }
            
            System.out.println("---------使用 For-Each 循环-------------");
            
            //增强的 for 循环 For-Each
            for(int element:arr)
            {
                System.out.println(element);
            }
            
            System.out.println("---------For-Each 循环二维数组-------------");
            
            //遍历二维数组
            int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ;
            for(int[] row : arr2)
            {
                for(int element : row)
                {
                    System.out.println(element);
                }
            }
            
            //以三种方式遍历集合 List
            List<String> list = new ArrayList<String>();
            
            list.add("Google");
            list.add("Runoob");
            list.add("Taobao");
            
            System.out.println("----------方式1:普通for循环-----------");
            for(int i = 0; i < list.size(); i++)
            {
                System.out.println(list.get(i));
            }
            
            System.out.println("----------方式2:使用迭代器-----------");
            for(Iterator<String> iter = list.iterator(); iter.hasNext();)
            {
                System.out.println(iter.next());
            }
            
            System.out.println("----------方式3:For-Each 循环-----------");
            for(String str: list)
            {
                System.out.println(str);
            }
        }
    }
    

    14.Java 实例 – Varargs 可变参数使用

    public class Main {
        static int  sumvarargs(int... intArrays){
            int sum, i;
            sum=0;
            for(i=0; i< intArrays.length; i++) {
                sum += intArrays[i];
            }
            return(sum);
        }
        public static void main(String args[]){
            int sum=0;
            sum = sumvarargs(new int[]{10,12,33});
            System.out.println("数字相加之和为: " + sum);
        }
    }
    

    15.Java 实例 – 重载(overloading)方法中使用 Varargs

    public class Main {
        static void vaTest(int ... no) {
            System.out.print("vaTest(int ...): " 
            + "参数个数: " + no.length +" 内容: ");
            for(int n : no)
            System.out.print(n + " ");
            System.out.println();
        }
        static void vaTest(boolean ... bl) {
            System.out.print("vaTest(boolean ...) " +
            "参数个数: " + bl.length + " 内容: ");
            for(boolean b : bl)
            System.out.print(b + " ");
            System.out.println();
        }
        static void vaTest(String msg, int ... no) {
            System.out.print("vaTest(String, int ...): " +
            msg +"参数个数: "+ no.length +" 内容: ");
            for(int  n : no)
            System.out.print(n + " ");
            System.out.println();
        }
        public static void main(String args[]){
            vaTest(1, 2, 3);
            vaTest("测试: ", 10, 20);
            vaTest(true, false, false);
        }
    }
    

    五.打印图形

    1.Java 实例 – 打印菱形

    public class Diamond {
        public static void main(String[] args) {
            print(8); // 输出 8 行的菱形
        }
     
        public static void print(int size) {
            if (size % 2 == 0) {
                size++; // 计算菱形大小
            }
            for (int i = 0; i < size / 2 + 1; i++) {
                for (int j = size / 2 + 1; j > i + 1; j--) {
                    System.out.print(" "); // 输出左上角位置的空白
                }
                for (int j = 0; j < 2 * i + 1; j++) {
                    System.out.print("*"); // 输出菱形上半部边缘
                }
                System.out.println(); // 换行
            }
            for (int i = size / 2 + 1; i < size; i++) {
                for (int j = 0; j < i - size / 2; j++) {
                    System.out.print(" "); // 输出菱形左下角空白
                }
                for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {
                    System.out.print("*"); // 输出菱形下半部边缘
                }
                System.out.println(); // 换行
            }
        }
    }
    

    2.Java 实例 – 九九乘法表

    public class MultiplicationTable {
        public static void main(String[] args) {
            for(int i=1;i<=9;i++) {
                for(int j=1;j<=i;j++) {
                    System.out.print(j+"×"+i+"="+i*j+"\t");// \t 跳到下一个TAB位置
                }
                System.out.println();
            }
        }
    }
    

    3.Java 实例 – 打印三角形

    class Demo{
        public static void main(String[] args){
            for(int i=1;i<=5;i++){
                for(int j=5; i<=j; j--)
                    System.out.print(" ");
                for(int j=1; j<=i; j++)
                    System.out.print("*");
                for(int j=1; j<i; j++)
                    System.out.print("*");
                System.out.println();
            }
        }
    }
    

    4.Java 实例 – 打印倒立的三角形

    public class InvertedTriangle {
        public static void main(String[] args) {
             //打印倒立的三角形
            for (int m = 1; m <= 4; m++) {
                //打印空格
                for (int n = 0; n <= m; n++) {
                    System.out.print(" ");
                }
                //打印*
                for (int x = 1; x <= 7 -2 * (m - 1); x++) {
                    System.out.print("*");
                }
                System.out.println();
            }        
        }
    }
    

    5.Java 实例 – 打印平行四边形

    public class Parallelogram {
        public static void main(String[] args) {
             //外层循环 每次打出一个*
            for (int i = 1; i <=5; i++) {
                //填充空格
                for (int j = 1; j <= 5 - i; j++) {
                    System.out.print(" ");
                }
                //内层循环 每次打印一个*
                for (int k = 1; k <= 5; k++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }
    

    6.Java 实例 – 打印矩形

    public class Rect {
        public static void main(String[] args) {
             //外层循环 每次输出一行*
            for (int i = 1; i <= 5; i++) {
                System.out.print("*");
                //内层循环 每次输出一个*
                for (int j = 1; j <= 5; j++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }
    

    六.Java 文件操作

    1.Java 实例 – 文件写入

    /*
     author by runoob.com 
     Main.java
     */
     
    import java.io.*;
     
    public class Main {
        public static void main(String[] args)  {
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter("runoob.txt"));
                out.write("菜鸟教程");
                out.close();
                System.out.println("文件创建成功!");
            } catch (IOException e) {
            }
        }
    }
    

    2.Java 实例 – 读取文件内容

    import java.io.*;
     
    public class Main {
        public static void main(String[] args)  {
            try {
                BufferedReader in = new BufferedReader(new FileReader("test.log"));
                String str;
                while ((str = in.readLine()) != null) {
                    System.out.println(str);
                }
                System.out.println(str);
            } catch (IOException e) {
            }
        }
    }
    

    3.Java 实例 – 删除文件

    import java.io.*;
     
    public class Main
    {
        public static void main(String[] args)
        {
            try{
                File file = new File("c:\\test.txt");
                if(file.delete()){
                    System.out.println(file.getName() + " 文件已被删除!");
                }else{
                    System.out.println("文件删除失败!");
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    

    4.Java 实例 – 将文件内容复制到另一个文件

    import java.io.*;
     
    public class Main {
        public static void main(String[] args) throws Exception {
            BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
            out1.write("string to be copied\n");
            out1.close();
            InputStream in = new FileInputStream(new File("srcfile"));
            OutputStream out = new FileOutputStream
            (new File("destnfile"));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
            String str;
            while ((str = in1.readLine()) != null) {
                System.out.println(str);
            }
            in1.close();
        }
    }
    

    5.Java 实例 – 向文件中追加数据

    import java.io.*;
     
    public class Main {
        public static void main(String[] args) throws Exception {
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
                out.write("aString1\n");
                out.close();
                out = new BufferedWriter(new FileWriter("filename",true));
                out.write("aString2");
                out.close();
                BufferedReader in = new BufferedReader(new FileReader("filename"));
                String str;
                while ((str = in.readLine()) != null) {
                    System.out.println(str);
                }
                in.close();
            }
                catch (IOException e) {
                System.out.println("exception occoured"+ e);
            }
        }
    }
    

    6.Java 实例 – 创建临时文件

    import java.io.*;
     
    public class Main {
        public static void main(String[] args) throws Exception {
            File temp = File.createTempFile("testrunoobtmp", ".txt");
            System.out.println("文件路径: "+temp.getAbsolutePath());
            temp.deleteOnExit();
            BufferedWriter out = new BufferedWriter(new FileWriter(temp));
            out.write("aString");
            System.out.println("临时文件已创建:");
            out.close();
        }
    }
    

    7.Java 实例 – 修改文件最后的修改日期

    import java.io.File;
    import java.util.Date;
     
    public class Main {
        public static void main(String[] args) throws Exception {
            File fileToChange = new File("C:/myjavafile.txt");
            fileToChange.createNewFile();
            Date filetime = new Date(fileToChange.lastModified());
            System.out.println(filetime.toString());
            System.out.println(fileToChange.setLastModified(System.currentTimeMillis()));
            filetime = new Date(fileToChange.lastModified());
            System.out.println(filetime.toString());
        }
    }
    

    8.Java 实例 – 获取文件大小

    import java.io.File;
     
    public class Main {
        public static long getFileSize(String filename) {
            File file = new File(filename);
            if (!file.exists() || !file.isFile()) {
                System.out.println("文件不存在");
                return -1;
            }
            return file.length();
        }
        public static void main(String[] args) {
            long size = getFileSize("c:/java.txt");
            System.out.println("java.txt文件大小为: " + size);
        }
    }
    

    9.Java 实例 – 文件重命名

    import java.io.File;
    import java.io.IOException;
     
    public class RunoobTest {
        public static void main(String[] args) throws IOException {
            // 旧的文件或目录
            File oldName = new File("./runoob-test.txt");
            // 新的文件或目录
            File newName = new File("./runoob-test-2.txt");
            if (newName.exists()) {  //  确保新的文件名不存在
                throw new java.io.IOException("file exists");
            }
            if(oldName.renameTo(newName)) {
                System.out.println("已重命名");
            } else {
                System.out.println("Error");
            }
        }
    }
    

    10.Java 实例 – 设置文件只读

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) {
            File file = new File("C:/java.txt");
            System.out.println(file.setReadOnly());
            System.out.println(file.canWrite());
        }
    }
    

    11.Java 实例 – 检测文件是否存在

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) {
            File file = new File("C:/java.txt");
            System.out.println(file.exists());
        }
    }
    

    12.Java 实例 – 在指定目录中创建文件

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) throws Exception {
            File file = null;
            File dir = new File("C:/");
            file = File.createTempFile
            ("JavaTemp", ".javatemp", dir);
            System.out.println(file.getPath());
        }
    }
    

    13.Java 实例 – 获取文件修改时间

    import java.io.File;
    import java.util.Date;
     
    public class Main {
        public static void main(String[] args) {
            File file = new File("Main.java");
            Long lastModified = file.lastModified();
            Date date = new Date(lastModified);
            System.out.println(date);
        }
    }
    

    14.Java 实例 – 创建文件

    import java.io.File;
    import java.io.IOException;
     
    public class Main {
        public static void main(String[] args) {
            try{
                File file = new File("C:/myfile.txt");
                if(file.createNewFile())
                    System.out.println("文件创建成功!");
                else
                    System.out.println("出错了,该文件已经存在。");
            }
            catch(IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    

    15.Java 实例 – 文件路径比较

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) {
            File file1 = new File("C:/File/demo1.txt");
            File file2 = new File("C:/java/demo1.txt");
            if(file1.compareTo(file2) == 0) {
                System.out.println("文件路径一致!");
            } else {
                System.out.println("文件路径不一致!");
            }
        }
    }
    

    七.Java 目录操作

    1.Java 实例 – 递归创建目录

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) {
            String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
            File file = new File(directories);
            boolean result = file.mkdirs();
            System.out.println("Status = " + result);
        }
    }
    

    2.Java 实例 – 删除目录

    import java.io.File;
     
    public class Main {
        public static void main(String[] argv) throws Exception {
            // 删除当前目录下的 test 目录
            deleteDir(new File("./test"));
        }
        public static boolean deleteDir(File dir) {
            if (dir.isDirectory()) {
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++) {
                    boolean success = deleteDir
                    (new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
            if(dir.delete()) {
                System.out.println("目录已被删除!");
                return true;
            } else {
                System.out.println("目录删除失败!");
                return false;
            }
        }
    }
    

    3.Java 实例 – 判断目录是否为空

    import java.io.File;
     
    public class Main
    {
        public static void main(String[] args)
        {
            File file = new File("./testdir");  // 当前目录下的 testdir目录
            if(file.isDirectory()){
                if(file.list().length>0){
                    System.out.println("目录不为空!");
                }else{
                    System.out.println("目录为空!");
                }
            }else{
                System.out.println("这不是一个目录!");
            }
        }
    }
    

    4.Java 实例 – 判断文件是否隐藏

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) {
            File file = new File("C:/Demo.txt");
            System.out.println(file.isHidden());
        }
    }
    

    5.Java 实例 – 获取目录大小

    import java.io.File;
    import org.apache.commons.io.FileUtils;
     
    public class Main {
        public static void main(String[] args) {
            long size = FileUtils.sizeOfDirectory(new File("C:/test"));
            System.out.println("Size: " + size + " bytes");
        }
    }
    

    6.Java 实例 – 在指定目录中查找文件

    import java.io.File;
     
    public class Main {
        public static void main(String[] argv) throws Exception {
            File dir = new File("../java");
            String[] children = dir.list();
            if (children == null) {
                System.out.println("该目录不存在");
            }
            else {
                for (int i = 0; i < children.length; i++) {
                    String filename = children[i];
                    System.out.println(filename);
                }
            }
        }
    }
    

    7.Java 实例 – 获取文件的上级目录

    import java.io.File;
     
    public class Main {
        public static void main(String[] args) {
            File file = new File("C:/File/demo.txt");
            String strParentDirectory = file.getParent();
            System.out.println("文件的上级目录为 : " + strParentDirectory);
        }
    }
    

    8.Java 实例 – 获取目录最后修改时间

    import java.io.File;
    import java.util.Date;
     
    public class Main {
        public static void main(String[] args) {
            File file = new File("C://FileIO//demo.txt");
            System.out.println("最后修改时间:" + new Date(file.lastModified()));
        }
    }
    

    9.Java 实例 – 打印目录结构

    import java.io.File;
    import java.io.IOException;
     
    public class FileUtil {
        public static void main(String[] a)throws IOException{
            showDir(1, new File("d:\\Java"));
        }
        static void showDir(int indent, File file) throws IOException {
            for (int i = 0; i < indent; i++)
                System.out.print('-');
            System.out.println(file.getName());
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++)
                    showDir(indent + 4, files[i]);
            }
        }
    }
    

    10.Java 实例 – 遍历指定目录下的所有目录

    import java.io.*;
     
    class Main {
       public static void main(String[] args) {
          File dir = new File("F:");
          File[] files = dir.listFiles();
          FileFilter fileFilter = new FileFilter() {
             public boolean accept(File file) {
                return file.isDirectory();
             }
          };
          files = dir.listFiles(fileFilter);
          System.out.println(files.length);
          if (files.length == 0) {
             System.out.println("目录不存在或它不是一个目录");
          }
          else {
             for (int i=0; i< files.length; i++) {
                File filename = files[i];
                System.out.println(filename.toString());
             }
          }
       }
    }
    

    11.Java 实例 – 遍历指定目录下的所有文件

    import java.io.File;
     
    class Main {
        public static void main(String[] args) {
            File dir = new File("C:");
            String[] children = dir.list();
            if (children == null) {
                System.out.println( "目录不存在或它不是一个目录");
            }
            else {
                for (int i=0; i< children.length; i++) {
                    String filename = children[i];
                    System.out.println(filename);
                }
            }
        }
    }
    

    12.Java 实例 – 在指定目录中查找文件

    import java.io.*;
     
    class Main {
       public static void main(String[] args) {
          File dir = new File("C:");
          FilenameFilter filter = new FilenameFilter() {
             public boolean accept
             (File dir, String name) {
                return name.startsWith("b");
            }
          };
          String[] children = dir.list(filter);
          if (children == null) {
             System.out.println("目录不存在或它不是一个目录");
          } 
          else {
             for (int i=0; i < children.length; i++) {
                String filename = children[i];
                System.out.println(filename);
             }
          } 
       }
    }
    

    13.Java 实例 – 遍历系统根目录

    import java.io.*;
     
    class Main{
        public static void main(String[] args){
            File[] roots = File.listRoots();
            System.out.println("系统所有根目录:");
            for (int i=0; i < roots.length; i++) {
                System.out.println(roots[i].toString());
            }
        }
    }
    

    14.Java 实例 – 查看当前工作目录

    class Main {
        public static void main(String[] args) {
            String curDir = System.getProperty("user.dir");
            System.out.println("你当前的工作目录为 :" + curDir);
        }
    }
    

    15.Java 实例 – 遍历目录

    import java.io.File;
     
    public class Main {
        public static void main(String[] argv) throws Exception {
            System.out.println("遍历目录");
            File dir = new File("/www/java"); //要遍历的目录
            visitAllDirsAndFiles(dir);
        }
        public static void visitAllDirsAndFiles(File dir) {
            System.out.println(dir);
            if (dir.isDirectory()) {
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++) {
                    visitAllDirsAndFiles(new File(dir, children[i]));
                }
            }
        }
    }
    

    八.Java 异常处理

    1.Java 实例 – 异常处理方法

    class ExceptionDemo
    {
        public static void main(String[] args) {
            try {
                throw new Exception("My Exception");
            } catch (Exception e) {
                System.err.println("Caught Exception");
                System.err.println("getMessage():" + e.getMessage());
                System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
                System.err.println("toString():" + e);
                System.err.println("printStackTrace():");
                e.printStackTrace();
            }
        }
    }
    

    2.Java 实例 – 多个异常处理(多个catch)

    class Demo  
    {  
        int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明该功能可能出现问题  
        {  
            int []arr = new int [a];  
      
            System.out.println(arr[4]);//制造的第一处异常  
      
            return a/b;//制造的第二处异常  
        }  
    }  
      
      
    class ExceptionDemo  
    {  
        public static void main(String[]args) //throws Exception  
        {  
            Demo d = new Demo();  
      
            try  
                {  
                    int x = d.div(4,0);//程序运行截图中的三组示例 分别对应此处的三行代码  
                    //int x = d.div(5,0);  
                    //int x = d.div(4,1);  
                    System.out.println("x="+x);   
            }  
            catch (ArithmeticException e)  
            {  
                System.out.println(e.toString());  
            }  
            catch (ArrayIndexOutOfBoundsException e)  
            {  
                System.out.println(e.toString());  
            }  
            catch (Exception e)//父类 写在此处是为了捕捉其他没预料到的异常 只能写在子类异常的代码后面  
                                //不过一般情况下是不写的   
            {  
                System.out.println(e.toString());  
            }  
              
      
      
            System.out.println("Over");  
        }  
      
    }
    

    3.Java 实例 – Finally的用法

    public class ExceptionDemo2 {
       public static void main(String[] argv) {
          new ExceptionDemo2().doTheWork();
       }
       public void doTheWork() {
          Object o = null;
          for (int i=0; i<5; i++) {
             try {
                o = makeObj(i);
             }
             catch (IllegalArgumentException e) {
                System.err.println
                ("Error: ("+ e.getMessage()+").");
                return;   
             }
             finally {
                System.err.println("都已执行完毕");
                if (o==null)
                System.exit(0);
            }
            System.out.println(o); 
          }
       }
       public Object makeObj(int type) 
       throws IllegalArgumentException {
          if (type == 1)  
          throw new IllegalArgumentException
          ("不是指定的类型: " + type);
          return new Object();
       }
    }
    

    4.Java 实例 – 使用 catch 处理异常

    public class Main {
        public static void main (String args[]) {
            int array[]={20,20,40};
            int num1=15,num2=10;
            int result=10;
            try{
                result = num1/num2;
                System.out.println("结果为 " +result);
                for(int i =5;i >=0; i--) {
                    System.out.println ("数组的元素值为 " +array[i]);
                }
            }
            catch (Exception e) {
                System.out.println("触发异常 : "+e);
            }
        }
    }
    

    5.Java 实例 – 多线程异常处理

    class MyThread extends Thread{
        public void run(){
            System.out.println("Throwing in " +"MyThread");
            throw new RuntimeException();
        }
    }
    class Main {
        public static void main(String[] args){
            MyThread t = new MyThread();
            t.start();
            try{
                Thread.sleep(1000);
            }
            catch (Exception x){
                System.out.println("Caught it" + x);
            }
            System.out.println("Exiting main");
        }
    }
    

    6.Java 实例 – 获取异常的堆栈信息

    public class Main{
        public static void main (String args[]){
            int array[]={20,20,40};
            int num1=15,num2=10;
            int result=10;
            try{
                result = num1/num2;
                System.out.println("The result is" +result);
                for(int i =5; i>=0; i--) {
                    System.out.println("The value of array is" +array[i]);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    7.Java 实例 – 重载方法异常处理

    public class Main {
        double method(int i) throws Exception{
            return i/0;
        }
        boolean method(boolean b) {
            return !b;
        }
        static double method(int x, double y) throws Exception  {
            return x + y ;
        }
        static double method(double x, double y) {
            return x + y - 3;
        }   
        public static void main(String[] args) {
            Main mn = new Main();
            try{
                System.out.println(method(10, 20.0));
                System.out.println(method(10.0, 20));
                System.out.println(method(10.0, 20.0));
                System.out.println(mn.method(10));
            }
            catch (Exception ex){
                System.out.println("exception occoure: "+ ex);
            }
        }
    }
    

    8.Java 实例 – 链试异常

    public class Main {
        public static void main (String args[])throws Exception  {
            int n=20,result=0;
            try{
                result=n/0;
                System.out.println("结果为"+result);
            }
            catch(ArithmeticException ex){
                System.out.println("发算术异常: "+ex);
                try {
                    throw new NumberFormatException();
                }
                catch(NumberFormatException ex1) {
                    System.out.println("手动抛出链试异常 : "+ex1);
                }
            }
        }
    }
    

    9.Java 实例 – 自定义异常

    class WrongInputException extends Exception {  // 自定义的类
        WrongInputException(String s) {
            super(s);
        }
    }
    class Input {
        void method() throws WrongInputException {
            throw new WrongInputException("Wrong input"); // 抛出自定义的类
        }
    }
    class TestInput {
        public static void main(String[] args){
            try {
                new Input().method();
            }
            catch(WrongInputException wie) {
                System.out.println(wie.getMessage());
            }
        } 
    }
    

    九.Java 数据结构

    1.Java 实例 – 数字求和运算

    public class Main {
        public static void main(String[] args) {
            int limit=100;
            int sum=0;
            int i=1;
            do
            {
                sum=sum+i;
                i++;
            }
            while(i<=limit);
            System.out.println("sum="+sum);
        }
    }
    

    2.Java 实例 – 利用堆栈将中缀表达式转换成后缀

    import java.io.IOException;
     
    public class InToPost {
       private Stack theStack;
       private String input;
       private String output = "";
       public InToPost(String in) {
          input = in;
          int stackSize = input.length();
          theStack = new Stack(stackSize);
       }
       public String doTrans() {
          for (int j = 0; j < input.length(); j++) {
             char ch = input.charAt(j);
             switch (ch) {
                case '+': 
                case '-':
                gotOper(ch, 1); 
                break; 
                case '*': 
                case '/':
                gotOper(ch, 2); 
                break; 
                case '(': 
                theStack.push(ch);
                break;
                case ')': 
                gotParen(ch); 
                break;
                default: 
                output = output + ch; 
                break;
             }
          }
          while (!theStack.isEmpty()) {
             output = output + theStack.pop();
          }
          System.out.println(output);
          return output; 
       }
       public void gotOper(char opThis, int prec1) {
          while (!theStack.isEmpty()) {
             char opTop = theStack.pop();
             if (opTop == '(') {
                theStack.push(opTop);
                break;
             }
             else {
                int prec2;
                if (opTop == '+' || opTop == '-')
                prec2 = 1;
                else
                prec2 = 2;
                if (prec2 < prec1) { 
                   theStack.push(opTop);
                   break;
                }
                else
                output = output + opTop;
             }
          }
          theStack.push(opThis);
       }
       public void gotParen(char ch){ 
          while (!theStack.isEmpty()) {
             char chx = theStack.pop();
             if (chx == '(') 
             break; 
             else
             output = output + chx; 
          }
       }
       public static void main(String[] args) 
       throws IOException {
          String input = "1+2*4/5-7+3/6";
          String output;
          InToPost theTrans = new InToPost(input);
          output = theTrans.doTrans(); 
          System.out.println("Postfix is " + output + '\n');
       }
       class Stack {
          private int maxSize;
          private char[] stackArray;
          private int top;
          public Stack(int max) {
             maxSize = max;
             stackArray = new char[maxSize];
             top = -1;
          }
          public void push(char j) {
             stackArray[++top] = j;
          }
          public char pop() {
             return stackArray[top--];
          }
          public char peek() {
             return stackArray[top];
          }
          public boolean isEmpty() {
             return (top == -1);
         }
       }
    }
    

    3.Java 实例 – 在链表(LinkedList)的开头和结尾

    import java.util.LinkedList;
     
    public class Main {
        public static void main(String[] args) {
            LinkedList<String> lList = new LinkedList<String>();
            lList.add("1");
            lList.add("2");
            lList.add("3");
            lList.add("4");
            lList.add("5");
            System.out.println(lList);
            lList.addFirst("0");
            System.out.println(lList);
            lList.addLast("6");
            System.out.println(lList);
        }
    }
    

    4.Java 实例 – 获取链表(LinkedList)的第一个

    import java.util.LinkedList;
     
    public class Main {
        public static void main(String[] args) {
            LinkedList<String> lList = new LinkedList<String>();
            lList.add("100");
            lList.add("200");
            lList.add("300");
            lList.add("400");
            lList.add("500");
            System.out.println("链表的第一个元素是:" + lList.getFirst());
            System.out.println("链表的最后一个元素是:" + lList.getLast());
        }
    }
    

    5.Java 实例 – 删除链表中的元素

    import java.util.*;
     
    public class Main {
       public static void main(String[] args) {
          LinkedList<String> lList = new LinkedList<String>();
          lList.add("1");
          lList.add("8");
          lList.add("6");
          lList.add("4");
          lList.add("5");
          System.out.println(lList);
          lList.subList(2, 4).clear();
          System.out.println(lList);
       }
    }
    

    6.Java 实例 – 获取链表的元素

    import java.util.*;
     
    public class Main {
       private LinkedList list = new LinkedList();
       public void push(Object v) {
          list.addFirst(v);
       }
       public Object top() {
          return list.getFirst();
       }
       public Object pop() {
          return list.removeFirst();
       }
       public static void main(String[] args) {
          Main stack = new Main();
          for (int i = 30; i < 40; i++)
             stack.push(new Integer(i));
          System.out.println(stack.top());
          System.out.println(stack.pop());
          System.out.println(stack.pop());
          System.out.println(stack.pop());
       }
    }
    

    7.Java 实例 – 获取向量元素的索引值

    import java.util.Collections;
    import java.util.Vector;
     
    public class Main {
       public static void main(String[] args) {
          Vector v = new Vector();
          v.add("X");
          v.add("M");
          v.add("D");
          v.add("A");
          v.add("O");
          Collections.sort(v);
          System.out.println(v);
          int index = Collections.binarySearch(v, "D");
          System.out.println("元素索引值为 : " + index);
       }
    }
    

    8.Java 实例 – 栈的实现

    ]`public class MyStack {
       private int maxSize;
       private long[] stackArray;
       private int top;
       public MyStack(int s) {
          maxSize = s;
          stackArray = new long[maxSize];
          top = -1;
       }
       public void push(long j) {
          stackArray[++top] = j;
       }
       public long pop() {
          return stackArray[top--];
       }
       public long peek() {
          return stackArray[top];
       }
       public boolean isEmpty() {
          return (top == -1);
       }
       public boolean isFull() {
          return (top == maxSize - 1);
       }
       public static void main(String[] args) {
          MyStack theStack = new MyStack(10); 
          theStack.push(10);
          theStack.push(20);
          theStack.push(30);
          theStack.push(40);
          theStack.push(50);
          while (!theStack.isEmpty()) {
             long value = theStack.pop();
             System.out.print(value);
             System.out.print(" ");
          }
          System.out.println("");
       }
    }`
    

    9.Java 实例 – 链表元素查找

    import java.util.LinkedList;
     
    public class Main {
       public static void main(String[] args) {
          LinkedList lList = new LinkedList();
          lList.add("1");
          lList.add("2");
          lList.add("3");
          lList.add("4");
          lList.add("5");
          lList.add("2");
          System.out.println("元素 2 第一次出现的位置:" + lList.indexOf("2"));
          System.out.println("元素 2 最后一次出现的位置:"+ lList.lastIndexOf("2"));
       }
    }
    

    10.Java 实例 – 压栈出栈的方法实现字符串反转

    import java.io.IOException;
     
    public class StringReverserThroughStack {
       private String input; 
       private String output;
       public StringReverserThroughStack(String in) {
          input = in;
       }
       public String doRev() {
          int stackSize = input.length(); 
          Stack theStack = new Stack(stackSize); 
          for (int i = 0; i < input.length(); i++) {
             char ch = input.charAt(i); 
             theStack.push(ch); 
          }
          output = "";
          while (!theStack.isEmpty()) {
             char ch = theStack.pop(); 
             output = output + ch; 
          }
          return output;
       }
       public static void main(String[] args) 
       throws IOException {
          String input = "www.w3cschool.cc";
          String output;
          StringReverserThroughStack theReverser = 
          new StringReverserThroughStack(input);
          output = theReverser.doRev();
          System.out.println("反转前: " + input);
          System.out.println("反转后: " + output);
       }
       class Stack {
          private int maxSize;
          private char[] stackArray;
          private int top;
          public Stack(int max) {
             maxSize = max;
             stackArray = new char[maxSize];
             top = -1;
          }
          public void push(char j) {
             stackArray[++top] = j;
          }
          public char pop() {
             return stackArray[top--];
          }
          public char peek() {
             return stackArray[top];
          }
          public boolean isEmpty() {
             return (top == -1);
          }
       }
    }
    

    11.Java 实例 – 队列(Queue)用法

    import java.util.LinkedList;
    import java.util.Queue;
     
    public class Main {
        public static void main(String[] args) {
            //add()和remove()方法在失败的时候会抛出异常(不推荐)
            Queue<String> queue = new LinkedList<String>();
            //添加元素
            queue.offer("a");
            queue.offer("b");
            queue.offer("c");
            queue.offer("d");
            queue.offer("e");
            for(String q : queue){
                System.out.println(q);
            }
            System.out.println("===");
            System.out.println("poll="+queue.poll()); //返回第一个元素,并在队列中删除
            for(String q : queue){
                System.out.println(q);
            }
            System.out.println("===");
            System.out.println("element="+queue.element()); //返回第一个元素 
            for(String q : queue){
                System.out.println(q);
            }
            System.out.println("===");
            System.out.println("peek="+queue.peek()); //返回第一个元素 
            for(String q : queue){
                System.out.println(q);
            }
        }
    }
    

    12.Java 实例 – 获取向量的最大元素

    import java.util.Collections;
    import java.util.Vector;
     
    public class Main {
       public static void main(String[] args) {
          Vector v = new Vector();
          v.add(new Double("3.4324"));
          v.add(new Double("3.3532"));
          v.add(new Double("3.342"));
          v.add(new Double("3.349"));
          v.add(new Double("2.3"));
          Object obj = Collections.max(v);
          System.out.println("最大元素是:"+obj);
       }
    }
    

    13.Java 实例 – 链表修改

    import java.util.LinkedList;
     
    public class Main {
       public static void main(String[] a) {
          LinkedList officers = new LinkedList();
          officers.add("B");
          officers.add("B");
          officers.add("T");
          officers.add("H");
          officers.add("P");
          System.out.println(officers);
          officers.set(2, "M");
          System.out.println(officers);
       }
    }
    

    14.Java 实例 – 旋转向量

    import java.util.Collections;
    import java.util.Vector;
     
    public class Main {
       public static void main(String[] args) {
          Vector<String> v = new Vector();
          v.add("1");
          v.add("2");
          v.add("3");
          v.add("4");
          v.add("5");
          System.out.println(v);
          Collections.swap(v, 0, 4);
          System.out.println("旋转后");
          System.out.println(v);
       }
    }
    

    十.Java 集合

    1.Java 实例 – 数组转集合

    import java.util.*;
    import java.io.*;
     
    public class ArrayToCollection{
       public static void main(String args[]) 
       throws IOException{
          int n = 5;         // 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 + " ");
          }
       }
    }
    

    2.Java 实例 – 集合比较

    import java.util.Collections;
    import java.util.Set;
    import java.util.TreeSet;
     
    class Main {
        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));
        }
    }
    

    3.Java 实例 – HashMap遍历

    import java.util.*;
     
    public class Main {
       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());
         }
       }
    }
    

    4.Java 实例 – 集合长度

    import java.util.*;
     
    public class Main {
       public static void main(String [] args) {   
          System.out.println( "集合实例!\n" ); 
          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("集合是空的");
          }
          else{
             System.out.println( "集合长度: " + size);
          }
          System.out.println();
       }
    }
    

    5.Java 实例 – 集合打乱顺序

    import java.util.*;
     
    public class Main {
        public static void main(String[] args) {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < 10; i++)
                list.add(new Integer(i));
            System.out.println("打乱前:");
            System.out.println(list);
     
            for (int i = 1; i < 6; i++) {
                System.out.println("第" + i + "次打乱:");
                Collections.shuffle(list);
                System.out.println(list);
            }
        }
    }
    

    6.Java 实例 – 集合遍历

    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
     
    public class Main {
     
       public static void main(String[] args) {
          // List集合的遍历
          listTest();
          // Set集合的遍历
          setTest();
       }
     
       private static void setTest() {
          Set<String> set = new HashSet<String>();
          set.add("JAVA");
          set.add("C");
          set.add("C++");
          // 重复数据添加失败
          set.add("JAVA");
          set.add("JAVASCRIPT");
     
          // 使用iterator遍历set集合
          Iterator<String> it = set.iterator();
          while (it.hasNext()) {
             String value = it.next();
             System.out.println(value);
          }
          
          // 使用增强for循环遍历set集合
          for(String s: set){
             System.out.println(s);
          }
       }
     
       // 遍历list集合
       private static void listTest() {
          List<String> list = new ArrayList<String>();
          list.add("菜");
          list.add("鸟");
          list.add("教");
          list.add("程");
          list.add("www.runoob.com");
     
          // 使用iterator遍历
          Iterator<String> it = list.iterator();
          while (it.hasNext()) {
             String value = it.next();
             System.out.println(value);
          }
     
          // 使用传统for循环进行遍历
          for (int i = 0, size = list.size(); i < size; i++) {
             String value = list.get(i);
             System.out.println(value);
          }
     
          // 使用增强for循环进行遍历
          for (String value : list) {
             System.out.println(value);
          }
       }
    }
    

    7.Java 实例 – 集合反转

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.ListIterator;
     
    class Main {
       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("反转前");
          while (liter.hasNext())
             System.out.println(liter.next());
          Collections.reverse(l);
          liter = l.listIterator();
          System.out.println("反转后");
          while (liter.hasNext())
             System.out.println(liter.next());
       }
    }
    

    8.Java 实例 – 删除集合中指定元素

    import java.util.*;
     
    public class Main {
       public static void main(String [] args) {   
          System.out.println( "集合实例!\n" ); 
          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();
          collection.remove(str2);
          System.out.println("删除之后 [" + str2 + "]\n");
          System.out.print("现在集合的数据是: ");
          iterator = collection.iterator();     
          while (iterator.hasNext()){
             System.out.print(iterator.next() + " ");  
          }
          System.out.println();
          size = collection.size();
          System.out.println("集合大小: " + size + "\n");
       }
    }
    

    9.Java 实例 – 只读集合

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
     
    public class Main {
       public static void main(String[] argv) 
       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) {
          }
          Set set = new HashSet(stuff);
          set = Collections.unmodifiableSet(set);
          Map map = new HashMap();
          map = Collections.unmodifiableMap(map);
          System.out.println("集合现在是只读");
       }
    }
    

    10.Java 实例 – 集合输出

    import java.util.*;
     
    public class Main{
       public static void main(String[] args) {
          System.out.println("TreeMap 实例!\n");
          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("TreeMap 键:" 
          + tMap.keySet());
          System.out.println("TreeMap 值:" 
          + tMap.values());
          System.out.println("键为 5 的值为: " + tMap.get(5)+ "\n");
          System.out.println("第一个键: " + tMap.firstKey() 
          + " Value: " 
          + tMap.get(tMap.firstKey()) + "\n");
          System.out.println("最后一个键: " + tMap.lastKey() 
          + " Value: "+ tMap.get(tMap.lastKey()) + "\n");
          System.out.println("移除第一个数据: " 
          + tMap.remove(tMap.firstKey()));
          System.out.println("现在 TreeMap 键为: " 
          + tMap.keySet());
          System.out.println("现在 TreeMap 包含: " 
          + tMap.values() + "\n");
          System.out.println("移除最后一个数据: " 
          + tMap.remove(tMap.lastKey()));
          System.out.println("现在 TreeMap 键为: " 
          + tMap.keySet());
          System.out.println("现在 TreeMap 包含: " 
          + tMap.values());
       }
    }
    

    11.Java 实例 – 集合转数组

    import java.util.*;
     
    public class Main{
       public static void main(String[] args){
          List<String> list = new ArrayList<String>();
          list.add("菜"); 
          list.add("鸟"); 
          list.add("教");
          list.add("程");
          list.add("www.runoob.com");
          String[] s1 = list.toArray(new String[0]); 
          for(int i = 0; i < s1.length; ++i){
             String contents = s1[i];
             System.out.print(contents);
         } 
       }
    }
    

    12.Java 实例 – List 循环移动元素

    import java.util.*;
     
    public class Main {
       public static void main(String[] args) {
          List list = Arrays.asList("one Two three Four five six".split(" "));
          System.out.println("List :"+list);
          Collections.rotate(list, 3);
          System.out.println("rotate: " + list);
       }
    }
    

    13.Java 实例 – 查找 List 中的最大最小值

    import java.util.*;
     
    public class Main {
       public static void main(String[] args) {
          List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
          System.out.println(list);
          System.out.println("最大值: " + Collections.max(list));
          System.out.println("最小值: " + Collections.min(list));
       }
    }
    

    14.Java 实例 – 遍历 HashTable 的键值

    import java.util.Enumeration;
    import java.util.Hashtable;
     
    public class Main {
       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());
          }
       }
    }
    

    15.Java 实例 – 使用 Enumeration 遍历 HashTable

    import java.util.Enumeration;
    import java.util.Hashtable;
     
    public class Main {
       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.elements();
          while(e.hasMoreElements()){
             System.out.println(e.nextElement());
          }
       }
    }
    

    16.Java 实例 – 集合中添加不同类型元素

    import java.util.Map;
    import java.util.Set;
    import java.util.SortedMap;
    import java.util.SortedSet;
    import java.util.TreeMap;
    import java.util.TreeSet;
     
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.LinkedHashSet;
    import java.util.LinkedList;
    import java.util.List;
     
     
    public class Main {
       public static void main(String[] args) {
          List lnkLst = new LinkedList();
          lnkLst.add("element1");
          lnkLst.add("element2");
          lnkLst.add("element3");
          lnkLst.add("element4");
          displayAll(lnkLst);
          List aryLst = new ArrayList();
          aryLst.add("x");
          aryLst.add("y");
          aryLst.add("z");
          aryLst.add("w");
          displayAll(aryLst);
          Set hashSet = new HashSet();
          hashSet.add("set1");
          hashSet.add("set2");
          hashSet.add("set3");
          hashSet.add("set4");
          displayAll(hashSet);
          SortedSet treeSet = new TreeSet();
          treeSet.add("1");
          treeSet.add("2");
          treeSet.add("3");
          treeSet.add("4");
          displayAll(treeSet);
          LinkedHashSet lnkHashset = new LinkedHashSet();
          lnkHashset.add("one");
          lnkHashset.add("two");
          lnkHashset.add("three");
          lnkHashset.add("four");
          displayAll(lnkHashset);
          Map map1 = new HashMap();
          map1.put("key1", "J");
          map1.put("key2", "K");
          map1.put("key3", "L");
          map1.put("key4", "M");
          displayAll(map1.keySet());
          displayAll(map1.values());
          SortedMap map2 = new TreeMap();
          map2.put("key1", "JJ");
          map2.put("key2", "KK");
          map2.put("key3", "LL");
          map2.put("key4", "MM");
          displayAll(map2.keySet());
          displayAll(map2.values());
          LinkedHashMap map3 = new LinkedHashMap();
          map3.put("key1", "JJJ");
          map3.put("key2", "KKK");
          map3.put("key3", "LLL");
          map3.put("key4", "MMM");
          displayAll(map3.keySet());
          displayAll(map3.values());
       }
       static void displayAll(Collection col) {
          Iterator itr = col.iterator();
          while (itr.hasNext()) {
             String str = (String) itr.next();
             System.out.print(str + " ");
          }
          System.out.println();
       }
    }
    

    17.Java 实例 – List 元素替换

    import java.util.*;
     
    public class Main {
       public static void main(String[] args) {
          List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
          System.out.println("List :"+list);
          Collections.replaceAll(list, "one", "hundrea");
          System.out.println("replaceAll: " + list);
       }
    }
    

    18.Java 实例 – List 截取

    import java.util.*;
     
    public class Main {
       public static void main(String[] args) {
          List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
          System.out.println("List :"+list);
          List sublist = Arrays.asList("three Four".split(" "));
          System.out.println("子列表 :"+sublist);
          System.out.println("indexOfSubList: "
          + Collections.indexOfSubList(list, sublist));
          System.out.println("lastIndexOfSubList: "
          + Collections.lastIndexOfSubList(list, sublist));
       }
    }
    

    十一.Java 网络实例

    1.Java 实例 – 获取指定主机的IP地址

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

    2.Java 实例 – 查看端口是否已使用

    import java.net.*;
    import java.io.*;
     
    public class Main {
       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) {
             }
          }
       }
    }
    

    3.Java 实例 – 获取本机ip地址及主机名

    import java.net.InetAddress;
    import java.net.UnknownHostException;
     
    public class NetworkInfo {
        public static void main(String[] args) {
            try {
                // 获取本地主机对象
                InetAddress localHost = InetAddress.getLocalHost();
                
                // 获取主机名
                String hostName = localHost.getHostName();
                System.out.println("主机名: " + hostName);
                
                // 获取IP地址
                String hostAddress = localHost.getHostAddress();
                System.out.println("IP地址: " + hostAddress);
            } catch (UnknownHostException e) {
                System.err.println("无法获取本机IP地址及主机名: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    

    4.Java 实例 – 获取远程文件大小

    import java.net.URL;
    import java.net.URLConnection;
     
    public class Main {
       public static void main(String[] args) throws Exception {
          int size;
          URL url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");
          URLConnection conn = url.openConnection();
          size = conn.getContentLength();
          if (size < 0)
              System.out.println("无法获取文件大小。");
          else
            System.out.println("文件大小为:" + size + " bytes");
          conn.getInputStream().close();
       }
    }
    

    5.Java 实例 – Socket 实现多线程服务器程序

    import java.io.*;
    import java.net.*;
     
    public class MultiThreadedServer {
        public static void main(String[] args) {
            int port = 12345; // 定义服务器端口
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                System.out.println("服务器已启动,等待客户端连接...");
     
                while (true) {
                    Socket clientSocket = serverSocket.accept(); // 接受客户端连接
                    System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress());
     
                    // 为每个客户端连接启动一个新的线程
                    ClientHandler clientHandler = new ClientHandler(clientSocket);
                    new Thread(clientHandler).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
     
    class ClientHandler implements Runnable {
        private Socket clientSocket;
     
        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }
     
        @Override
        public void run() {
            try (
                InputStream input = clientSocket.getInputStream();
                OutputStream output = clientSocket.getOutputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                PrintWriter writer = new PrintWriter(output, true)
            ) {
                String clientMessage;
                while ((clientMessage = reader.readLine()) != null) {
                    System.out.println("收到客户端消息: " + clientMessage);
                    writer.println("服务器回应: " + clientMessage); // 发送回应消息给客户端
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    6.Java 实例 – 查看主机指定文件的最后修改时间

    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Date;
    import java.text.SimpleDateFormat;
     
    public class Main {
        public static void main(String[] argv) throws Exception {
            URL u = new URL("http://127.0.0.1/test/test.html");
            URLConnection uc = u.openConnection();
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
            uc.setUseCaches(false);
            long timestamp = uc.getLastModified();
            System.out.println("test.html 文件最后修改时间 :" + ft.format(new Date(timestamp)));
        }
    }
    

    7.Java 实例 – 使用 Socket 连接到指定主机

    import java.net.InetAddress;
    import java.net.Socket;
     
    public class WebPing {
        public static void main(String[] args) {
            try {
                InetAddress addr;
                Socket sock = new Socket("www.runoob.com", 80);
                addr = sock.getInetAddress();
                System.out.println("连接到 " + addr);
                sock.close();
            } catch (java.io.IOException e) {
                System.out.println("无法连接 " + args[0]);
                System.out.println(e);
            }
        }
    }
    

    8.Java 实例 – 网页抓取

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.net.URL;
     
    public class Main {
       public static void main(String[] args) 
       throws Exception {
          URL url = new URL("http://www.runoob.com");
          BufferedReader reader = new BufferedReader
          (new InputStreamReader(url.openStream()));
          BufferedWriter writer = new BufferedWriter
          (new FileWriter("data.html"));
          String line;
          while ((line = reader.readLine()) != null) {
             System.out.println(line);
             writer.write(line);
             writer.newLine();
          }
          reader.close();
          writer.close();
       }
    }
    

    9.Java 实例 – 获取 URL响应头的日期信息

    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Date;
     
    public class Main{
       public static void main(String args[]) 
       throws Exception {
          URL url = new URL("http://www.runoob.com");
          HttpURLConnection httpCon = 
          (HttpURLConnection) url.openConnection();
          long date = httpCon.getDate();
          if (date == 0)
          System.out.println("无法获取信息。");
          else
          System.out.println("Date: " + new Date(date));
       }
    }
    

    10.Java 实例 – 获取 URL 响应头信息

    import java.io.IOException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Map;
    import java.util.Set;
     
    public class Main {
        public static void main(String[] args) throws IOException{
            URL url = new URL("http://www.runoob.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() );
        }
    }
    

    11.Java 实例 – 解析 URL

    import java.net.URL;
     
    public class Main {
       public static void main(String[] args) 
       throws Exception {
          URL url = new URL("http://www.runoob.com/html/html-tutorial.html");
          System.out.println("URL 是 " + url.toString());
          System.out.println("协议是 " + url.getProtocol());
          System.out.println("文件名是 " + url.getFile());
          System.out.println("主机是 " + url.getHost());
          System.out.println("路径是 " + url.getPath());
          System.out.println("端口号是 " + url.getPort());
          System.out.println("默认端口号是 " 
          + url.getDefaultPort());
       }
    }
    

    12.Java 实例 – ServerSocket 和 Socket 通信实例

    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 Server {
       public static void main(String[] args) {
          try {
             ServerSocket ss = new ServerSocket(8888);
             System.out.println("启动服务器....");
             Socket s = ss.accept();
             System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
             
             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
             //读取客户端发送来的消息
             String mess = br.readLine();
             System.out.println("客户端:"+mess);
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
             bw.write(mess+"\n");
             bw.flush();
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    }
    
    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 Client {
       public static void main(String[] args) {
          try {
             Socket s = new Socket("127.0.0.1",8888);
             
             //构建IO
             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("服务器:"+mess);
          } catch (UnknownHostException e) {
             e.printStackTrace();
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    }
    

    十二.Java 线程

    1.Java 实例 – 查看线程是否存活

    public class TwoThreadAlive extends Thread {
       public void run() {
          for (int i = 0; i < 10; i++) {
             printMsg();
          }
       }
     
       public void printMsg() {
          Thread t = Thread.currentThread();
          String name = t.getName();
          System.out.println("name=" + name);
       }
     
       public static void main(String[] args) {
          TwoThreadAlive tt = new TwoThreadAlive();
          tt.setName("Thread");
          System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
          tt.start();
          System.out.println("just after start(), tt.isAlive()=" + tt.isAlive());
          for (int i = 0; i < 10; i++) {
             tt.printMsg();
          }
          System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());
       }
    }
    

    2.Java 实例 – 获取当前线程名称

    public class TwoThreadGetName extends Thread {
       public void run() {
          for (int i = 0; i < 10; i++) {
             printMsg();
          }
       }
       public void printMsg() {
          Thread t = Thread.currentThread();
          String name = t.getName();
          System.out.println("name=" + name);
       } 
       public static void main(String[] args) {
          TwoThreadGetName tt = new TwoThreadGetName();
          tt.start();
          for (int i = 0; i < 10; i++) {
             tt.printMsg();
          }
       }
    }
    

    3.Java 实例 – 状态监测

    class MyThread extends Thread{
       boolean waiting= true;
       boolean ready= false;
       MyThread() {
       }
       public void run() {
          String thrdName = Thread.currentThread().getName();
          System.out.println(thrdName + " starting.");
          while(waiting) 
          System.out.println("waiting:"+waiting); 
          System.out.println("waiting...");
          startWait(); 
          try {
             Thread.sleep(1000);
          }
          catch(Exception exc) {
             System.out.println(thrdName + " interrupted.");
          }
          System.out.println(thrdName + " terminating.");
       }
       synchronized void startWait() {
          try {
             while(!ready) wait();
          }
          catch(InterruptedException exc) {
             System.out.println("wait() interrupted");
          }
       }
       synchronized void notice() {
          ready = true;
          notify();
       }
    }
    public class Main {
       public static void main(String args[]) 
       throws Exception{
          MyThread thrd = new MyThread();
          thrd.setName("MyThread #1");
          showThreadStatus(thrd);
          thrd.start();
          Thread.sleep(50);
          showThreadStatus(thrd);
          thrd.waiting = false;
          Thread.sleep(50); 
          showThreadStatus(thrd);
          thrd.notice();
          Thread.sleep(50);
          showThreadStatus(thrd);
          while(thrd.isAlive()) 
          System.out.println("alive");
          showThreadStatus(thrd);
       }
       static void showThreadStatus(Thread thrd) {
          System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState());
       }
    }
    

    4.Java 实例 – 线程优先级设置

    public class SimplePriorities extends Thread {
       private int countDown = 5;
       private volatile double d = 0; 
       public SimplePriorities(int priority) {
          setPriority(priority);
          start();
       }
       public String toString() {
          return super.toString() + ": " + countDown;
       }
       public void run() {
          while(true) {
             for(int i = 1; i < 100000; i++)
             d = d + (Math.PI + Math.E) / (double)i;
             System.out.println(this);
             if(--countDown == 0) return;
          }
       }
       public static void main(String[] args) {
          new SimplePriorities(Thread.MAX_PRIORITY);
          for(int i = 0; i < 5; i++)
          new SimplePriorities(Thread.MIN_PRIORITY);
       }
    }
    

    5.Java 实例 – 死锁及解决方法

    import java.util.Date;
     
    public class LockTest {
       public static String obj1 = "obj1";
       public static String obj2 = "obj2";
       public static void main(String[] args) {
          LockA la = new LockA();
          new Thread(la).start();
          LockB lb = new LockB();
          new Thread(lb).start();
       }
    }
    class LockA implements Runnable{
       public void run() {
          try {
             System.out.println(new Date().toString() + " LockA 开始执行");
             while(true){
                synchronized (LockTest.obj1) {
                   System.out.println(new Date().toString() + " LockA 锁住 obj1");
                   Thread.sleep(3000); // 此处等待是给B能锁住机会
                   synchronized (LockTest.obj2) {
                      System.out.println(new Date().toString() + " LockA 锁住 obj2");
                      Thread.sleep(60 * 1000); // 为测试,占用了就不放
                   }
                }
             }
          } catch (Exception e) {
             e.printStackTrace();
          }
       }
    }
    class LockB implements Runnable{
       public void run() {
          try {
             System.out.println(new Date().toString() + " LockB 开始执行");
             while(true){
                synchronized (LockTest.obj2) {
                   System.out.println(new Date().toString() + " LockB 锁住 obj2");
                   Thread.sleep(3000); // 此处等待是给A能锁住机会
                   synchronized (LockTest.obj1) {
                      System.out.println(new Date().toString() + " LockB 锁住 obj1");
                      Thread.sleep(60 * 1000); // 为测试,占用了就不放
                   }
                }
             }
          } catch (Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    6.Java 实例 – 获取线程id

    public class Main extends Object implements Runnable {
      private ThreadID var;
     
      public Main(ThreadID v) {
        this.var = v;
      }
     
      public void run() {
        try {
          print("var getThreadID =" + var.getThreadID());
          Thread.sleep(2000);
          print("var getThreadID =" + var.getThreadID());
        } catch (InterruptedException x) {
        }
      }
     
      private static void print(String msg) {
        String name = Thread.currentThread().getName();
        System.out.println(name + ": " + msg);
      }
     
      public static void main(String[] args) {
        ThreadID tid = new ThreadID();
        Main shared = new Main(tid);
     
        try {
          Thread threadA = new Thread(shared, "threadA");
          threadA.start();
     
          Thread.sleep(500);
     
          Thread threadB = new Thread(shared, "threadB");
          threadB.start();
     
          Thread.sleep(500);
     
          Thread threadC = new Thread(shared, "threadC");
          threadC.start();
        } catch (InterruptedException x) {
        }
      }
    }
     
    class ThreadID extends ThreadLocal {
      private int nextID;
     
      public ThreadID() {
        nextID = 10001;
      }
     
      private synchronized Integer getNewID() {
        Integer id = new Integer(nextID);
        nextID++;
        return id;
      }
     
     
      protected Object initialValue() {
        print("in initialValue()");
        return getNewID();
      }
     
      public int getThreadID() {
        Integer id = (Integer) get();
        return id.intValue();
      }
     
      private static void print(String msg) {
        String name = Thread.currentThread().getName();
        System.out.println(name + ": " + msg);
      }
    }
    

    7.Java 实例 – 线程挂起

    public class SleepingThread extends Thread {
       private int countDown = 5;
       private static int threadCount = 0;
       public SleepingThread() {
          super("" + ++threadCount);
          start();
       }
       public String toString() { 
          return "#" + getName() + ": " + countDown;
       }
       public void run() {
          while (true) {
             System.out.println(this);
             if (--countDown == 0)
                return;
             try {
                sleep(100);
             }
             catch (InterruptedException e) {
                throw new RuntimeException(e);
             }
          }
       }
       public static void main(String[] args) 
       throws InterruptedException {
          for (int i = 0; i < 5; i++)
          new SleepingThread().join();
          System.out.println("线程已被挂起");
       }
    }
    

    8.Java 实例 – 终止线程

    public class ThreadInterrupt extends Thread 
    { 
        public void run() 
        { 
            try 
            { 
                sleep(50000);  // 延迟50秒 
            } 
            catch (InterruptedException e) 
            { 
                System.out.println(e.getMessage()); 
            } 
        } 
        public static void main(String[] args) throws Exception 
        { 
            Thread thread = new ThreadInterrupt(); 
            thread.start(); 
            System.out.println("在50秒之内按任意键中断线程!"); 
            System.in.read(); 
            thread.interrupt(); 
            thread.join(); 
            System.out.println("线程已经退出!"); 
        } 
    }
    

    9.Java 实例 – 生产者/消费者问题

    /*
     author by runoob.com
     ProducerConsumerTest.java
     */
    
    public class ProducerConsumerTest {
       public static void main(String[] args) {
          CubbyHole c = new CubbyHole();
          Producer p1 = new Producer(c, 1);
          Consumer c1 = new Consumer(c, 1);
          p1.start(); 
          c1.start();
       }
    }
    class CubbyHole {
       private int contents;
       private boolean available = false;
       public synchronized int get() {
          while (available == false) {
             try {
                wait();
             }
             catch (InterruptedException e) {
             }
          }
          available = false;
          notifyAll();
          return contents;
       }
       public synchronized void put(int value) {
          while (available == true) {
             try {
                wait();
             }
             catch (InterruptedException e) { 
             } 
          }
          contents = value;
          available = true;
          notifyAll();
       }
    }
    
    class Consumer extends Thread {
       private CubbyHole cubbyhole;
       private int number;
       public Consumer(CubbyHole c, int number) {
          cubbyhole = c;
          this.number = number;
       }
       public void run() {
          int value = 0;
             for (int i = 0; i < 10; i++) {
                value = cubbyhole.get();
                System.out.println("消费者 #" + this.number+ " got: " + value);
             }
        }
    }
    
    class Producer extends Thread {
       private CubbyHole cubbyhole;
       private int number;
    
       public Producer(CubbyHole c, int number) {
          cubbyhole = c;
          this.number = number;
       }
    
       public void run() {
          for (int i = 0; i < 10; i++) {
             cubbyhole.put(i);
             System.out.println("生产者 #" + this.number + " put: " + i);
             try {
                sleep((int)(Math.random() * 100));
             } catch (InterruptedException e) { }
          }
       }
    }
    

    10.Java 实例 – 获取线程状态

    // Java 程序 - 演示线程状态
    class thread implements Runnable 
    { 
        public void run() 
        { 
            //  thread2  - 超时等待
            try
            { 
                Thread.sleep(1500); 
            }  
            catch (InterruptedException e)  
            { 
                e.printStackTrace(); 
            } 
              
            System.out.println("State of thread1 while it called join() method on thread2 -"+ 
                Test.thread1.getState()); 
            try
            { 
                Thread.sleep(200); 
            }  
            catch (InterruptedException e)  
            { 
                e.printStackTrace(); 
            }      
        } 
    } 
      
    public class Test implements Runnable 
    { 
        public static Thread thread1; 
        public static Test obj; 
          
        public static void main(String[] args) 
        { 
            obj = new Test(); 
            thread1 = new Thread(obj); 
              
            // 创建 thread1,现在是初始状态
            System.out.println("State of thread1 after creating it - " + thread1.getState()); 
            thread1.start(); 
              
            // thread1 - 就绪状态
            System.out.println("State of thread1 after calling .start() method on it - " +  
                thread1.getState()); 
        } 
          
        public void run() 
        { 
            thread myThread = new thread(); 
            Thread thread2 = new Thread(myThread); 
              
            // 创建 thread1,现在是初始状态
            System.out.println("State of thread2 after creating it - "+ thread2.getState()); 
            thread2.start(); 
              
            // thread2 - 就绪状态
            System.out.println("State of thread2 after calling .start() method on it - " +  
                thread2.getState()); 
              
            // moving thread1 to timed waiting state 
            try
            { 
                //moving - 超时等待
                Thread.sleep(200); 
            }  
            catch (InterruptedException e)  
            { 
                e.printStackTrace(); 
            } 
            System.out.println("State of thread2 after calling .sleep() method on it - "+  
                thread2.getState() ); 
              
              
            try 
            { 
                // 等待 thread2 终止
                thread2.join(); 
            }  
            catch (InterruptedException e)  
            { 
                e.printStackTrace(); 
            } 
            System.out.println("State of thread2 when it has finished it's execution - " +  
                thread2.getState()); 
        } 
          
    }
    

    11.Java 实例 – 获取所有线程

    public class Main extends Thread {
       public static void main(String[] args) {
          Main t1 = new Main();
          t1.setName("thread1");
          t1.start();
          ThreadGroup currentGroup = 
          Thread.currentThread().getThreadGroup();
          int noThreads = currentGroup.activeCount();
          Thread[] lstThreads = new Thread[noThreads];
          currentGroup.enumerate(lstThreads);
          for (int i = 0; i < noThreads; i++)
          System.out.println("线程号:" + i + " = " + lstThreads[i].getName());
       }
    }
    

    12.Java 实例 – 查看线程优先级

    public class Main extends Object {
       private static Runnable makeRunnable() {
          Runnable r = new Runnable() {
             public void run() {
                for (int i = 0; i < 5; i++) {
                   Thread t = Thread.currentThread();
                   System.out.println("in run() - priority="
                   + t.getPriority()+ ", name=" + t.getName());
                   try {
                      Thread.sleep(2000);
                   }
                   catch (InterruptedException x) {
                   }
                }
             }
          };
          return r;
       }
       public static void main(String[] args) {
          System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority());
          System.out.println("in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName());
          Thread threadA = new Thread(makeRunnable(), "threadA");
          threadA.start();
          try {
             Thread.sleep(3000);
          }
          catch (InterruptedException x) {
          }
          System.out.println("in main() - threadA.getPriority()="+ threadA.getPriority());
       }
    }
    

    13.Java 实例 – 中断线程

    public class Main extends Object 
    implements Runnable {
       public void run() {
          try {
             System.out.println("in run() - 将运行 work2() 方法");
             work2();
             System.out.println("in run() - 从 work2() 方法回来");
          }
          catch (InterruptedException x) {
             System.out.println("in run() - 中断 work2() 方法");
             return;
          }
          System.out.println("in run() - 休眠后执行");
          System.out.println("in run() - 正常离开");
       }
       public void work2() throws InterruptedException {
          while (true) {
             if (Thread.currentThread().isInterrupted()) {
                System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
                Thread.sleep(2000);
                System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
             }
          }
       }
       public void work() throws InterruptedException {
          while (true) {
             for (int i = 0; i < 100000; i++) {
                int j = i * 2;
             }
             System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted());
             if (Thread.interrupted()) {
                System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
                throw new InterruptedException();
             }
          }
       }
       public static void main(String[] args) {
          Main si = new Main();
          Thread t = new Thread(si);
          t.start();
          try {
             Thread.sleep(2000);
          }
          catch (InterruptedException x) {
          }
          System.out.println("in main() - 中断其他线程");
          t.interrupt();
          System.out.println("in main() - 离开");
       }
    }
    

    作者:IS evening

    物联沃分享整理
    物联沃-IOTWORD物联网 » java菜鸟教程学习(完整版)

    发表回复