Java不完全教程第一章Java预备知识常用DOS命令help,dir,md,cd,rd,del,copy,move,start,type,cls,attrib配置环境变量JAVA_HOME C:\soft\Java\jdk1.6.0_37Path %JAVA_HOME%\bin第一个程序public class Hello {public static void main(String[] args) {System.out.println("Hello");}}Java三种注释文档注释 /***/多行注释 /**/单行注释 //启动记事本程序 - DEMOpublic static void main(String[] args) throws IOException {Runtime.getRuntime().exec("notepad");}第二章 Java基本语法Java常量 - 固定不变值Java变量 - 在内存中分配一块内存,用于保存数据空:      null基本数据类型布尔值:  boolean字符:    char整形:    byte,short,int,long浮点型:  float,double引用数据类型类:      String数组:    int[]类型转换自动转换 - 低字节类型数据和高字节类型数据参与运算会自动提升类型强制转换 - 将高字节数据强制转换成低字节数据,会丢失精度或者结果错误第三章 运算符与逻辑判断循环算数运算符 + - * / % ++ --赋值运算符 = += -= *= /= %=比较运算符 == != < > <= >= instanceof逻辑运算符 & | ^ ! && ||位运算符 & | ^ << >> >>>三元运算符 boolean?"":"";选择结构 if…else switch循环结构 for while do…while控制循环 continue break return在不知道x和y值的情况下,交换这个两个变量中的值int x=10, y=6; x+=y; y-=x; x+=y; y*=(-1); System.out.println(x+" "+y);int a=10, b=6; a+=b; b=a-b; a-=b; System.out.println(a+" "+b);int i=10, j=6; i^=j; j=i^j; i^=j; System.out.println(i+" "+j);在三个数中找到最大的那个数int x=10,y=20,z=30;int max = x>y?(x>z?x:z):(y>z?y:z);System.out.println(max);计算1+2+3+…+100的和int sum=0,i=0;for(;i<=100;sum+=i++);System.out.println(sum);sum=0;i=0;while(i<=100)sum+=i++;System.out.println(sum);sum=0;i=0;do{sum+=i++;}while(i<=100);System.out.println(sum);public static int sum = sum(100);public static int sum(int num) {return num==1?1:num+sum(num-1);}将十进制转换成二进制StringBuilder sb = new StringBuilder();System.out.println("请输入一个10进制数: ");int num = new Scanner(System.in).nextInt();while (num>0) {sb.append(num%2);num/=2;}sb.reverse();System.out.println(sb);第四章 函数和数组函数 - 代码在程序中需要多次使用,就可以定义成函数,在需要使用的时候调用函数的重载 - 函数名称相同,参数列表不同,返回值不同数组 - 类型一致长度不可变通过索引操作元素的容器数组相关函数Arrays.toString() 数组转换成字符串System.arraycopy() 数组深拷贝将数组中所有元素打印成一行并以逗号分割private static String arrayToString(int[] array) {if (array!=null && array.length>0) {String s = array[0]+"";for (int i = 1; i < array.length; i++) {s+=", "+array[i];}return s;}return "";}对数组进行排序 – 冒泡/选择private static int[] bubbleSort(int[] array) {int temp = 0;for (int i = 0; i < array.length-1; i++) {for (int j = i; 0 < j+1; j--) {if (array[j]<array[j+1]) {temp = array[j];array[j] = array[j+1];array[j+1] = temp;}}}return array;}private static int[] selectSort(int[] array) {int temp = 0;for (int i = 0; i < array.length-1; i++) {for (int j = i+1; j < array.length; j++) {if (array[i]<array[j]) {temp = array[i];array[i] = array[j];array[j] = temp;}}}return array;}对有序数组进行二分查找private static int binarySearch(int[] array, int key) {int start = 0;int end = array.length - 1;while (start <= end) {int middle = (start+end)/2;if (key > array[middle]) {start = middle + 1;}else if (key < array[middle]) {end = middle - 1;}else {return middle;}}return -1;}获取键盘输入的最大数public static void main(String[] args) throws Exception {int number = 0;System.out.println("请输入三个数字: ");BufferedReader br = new BufferedReader(new InputStreamReader(System.in));for (int i = 0; i < 3; i++) {int line = Integer.parseInt(br.readLine());number = line>number?line:number;}System.out.println(number);}递归求1+2+...public static int getSum(int n) {return n==1?1:getSum(n-1)+n;}第五章 面向对象封装 – 对内部变量私有化,对外部提供公有方法代码块 - 在创建对象时代码块会自动运行构造函数 – 函数名与类名相同没有返回值类型this - 那个对象调用该方法,this就代表那个对象static - 内存中对象是唯一的extends - 子类继承父类的方法和属性super - 子类调用父类的方法和属性向上转型 - 子类当做父类使用,不能调用子类特有的方法向下转型 - 子类当做父类使用,需要调用子类特有的方法,需要将父类强制转化成子类方法重写 - 子类必须与父类具有相同函数名,参数列表和返回值多态 – 将函数的形参定义为父类类型,传入不同的子类而实现不同的功能abstract – 父类定义抽象方法,需要在子类实现该方法final – 对象不能继承,方法不能重写,变量不能修改interface – 接口中所有的方法都需要在子类中实现implements – 一个类实现接口内部类 – 在一个类中嵌套另一个类package – 定义类所属的包import – 导入包中的类定义对象public class Person {private String name;private Integer age;}创建对象public static void main(String[] args) {Person p = new Person();}模拟电脑开/关机public class ComputerDemo {private static class Computer {private String name;private MainBoard mainBoard;private Boolean state;public Computer(){}public Computer(String name, MainBoard mainBoard) {this.name = name;this.mainBoard = mainBoard;this.state = false;}public void trunOn(){if(mainBoard==null){System.out.println(name+" 没有安装主板不能开机");}else{if (state) {return;}mainBoard.run();System.out.println(name+" 开机成功");state = true;}}public void trunOff(){if (state) {mainBoard.stop();System.out.println(name+" 关机成功");state = false;}else {System.out.println("电脑还没有开机");}}}private static class MainBoard {private String name;public MainBoard(){}public MainBoard(String name) {this.name = name;}public void run(){System.out.println(name+" 已启动");}public void stop() {System.out.println(name+" 停止运行");}}public static void main(String[] args) {Computer c = new Computer("ThinkPad T420", new MainBoard("华硕主板"));c.trunOn();c.trunOff();}}模拟超市购物@SuppressWarnings("unused")public class ShoppingDemo {private static class Product {private String name;public Product() {}public Product(String name) {this.name = name;}}private static class Market {private String name;private Product[] products;public Market(){}public Market(String name, Product[] products) {this.name = name;this.products = products;}public Product sell(String name){for (int i = 0; i < products.length; i++) {if (products[i].name == name) {return products[i];}}return null;}}private static class Person {private String name;public Person() {}public Person(String name) {this.name = name;}public Product shopping(Market market, String name){return market.sell(name);}}public static void main(String[] args) {Product p1 = new Product("电视机");Product p2 = new Product("洗衣机");Market m = new Market("家乐福",new Product[]{p1,p2});Person p = new Person("张三");Product result = p.shopping(m, "洗衣机");if (result!=null) {System.out.println("货物名称是:"+result.name);}else {System.out.println("没有此货物!");}}}模拟电脑USB设备public class Computer {private USB[] usbArray = new USB[4];private interface USB {void turnOn();}private static class Mouse implements USB {public void turnOn() {System.out.println("鼠标启动!");}}public void add(USB usb) {for (int i = 0; i < usbArray.length; i++) {if(usbArray[i]==null) {usbArray[i] = usb;break;}}}public void turnOn() {for (int i = 0; i < usbArray.length; i++) {if(usbArray[i]!=null) {usbArray[i].turnOn();}}}public static void main(String[] args) {Computer c = new Computer();c.add(new Mouse());c.turnOn();}}利用接口实现数值过滤public class Printer {private interface Filter {boolean accept(int i);}private static class OddFilter implements Filter{public boolean accept(int i) {return i%2!=0;}}public static void print(int[] array, Filter filter) {for (int i = 0; i < array.length; i++) {if (filter.accept(array[i])) {System.out.print(array[i]+" ");}}System.out.println();}public static void main(String[] args) {int[] array = {12,3,43,62,54};Printer.print(array, new OddFilter());}}单例设计模式 - 某个类对象只能被创建一次public class Singleton {private static final Singleton s = new Singleton();private Singleton(){}public static Singleton getInstance(){return s;}}组合设计模式 – 一个类需要用到另一个类的方法public class Composite {private static class Person {private Card card;public Person(Card card) {this.card = card;}}private static class Card {private int money;public Card(int money) {this.money = money;}}public static void main(String[] args) {Card card = new Card(1000);Person person = new Person(card);}}模板设计模式 – 经常做一些类似的事情就可以使用模板设计模式public abstract class Template {private static class Demo1 extends Template {public void doSomething() {System.out.println("测试1");}}private static class Demo2 extends Template {public void doSomething() {System.out.println("测试2");}}public final void test() {long start = System.currentTimeMillis();doSomething();long end = System.currentTimeMillis();System.out.println("耗时: "+(end-start)+"毫秒");}public abstract void doSomething();public static void main(String[] args) {new Demo1().test();new Demo2().test();}}装饰模式 - 对某个对象功能进行增强public class Wrapper {private interface Person {void run();void eat();void sleep();}private static class Man implements Person {public void run() {System.out.print("男人跑步!");}public void eat() {System.out.print("男人吃饭!");}public void sleep() {System.out.print("男人睡觉!");}}private static class SuperMan implements Person {private Man man;public SuperMan(Man man) {this.man = man;}public void run() {man.run();System.out.println("健步如飞!");}public void eat() {man.eat();System.out.println("狼吞虎咽!");}public void sleep() {man.sleep();System.out.println("鼾声如雷!");}}public static void main(String[] args) {Person person = new SuperMan(new Man());person.run();person.eat();person.sleep();}}适配器模式public class Adapter {public interface A {void a();void b();}public abstract static class B implements A {public void a() {}public void b() {}}public static void main(String[] args) {B b = new B(){public void a() {System.out.println("Adapter");}};b.a();}}第六章 异常和线程异常 – 程序运行时候出现的错误运行时异常 – RuntimeException 编译时不用处理编译时异常 – Exception 必须对异常代码进行处理throws – 声明异常throw – 抛出异常try – 捕获异常catch – 处理异常finally – 无论如何都会处理synchronized – 同步代码块自定义异常public class CustomException {private static class MyException extends Exception {public MyException(){super("自定义异常");}}public static void run() throws Exception{throw new MyException();}public static void main(String[] args) {try {run();} catch (Exception e) {throw new RuntimeException(e.getMessage(),e);} finally {System.out.println("测试是否执行!");}}}开启新的线程public class ThreadTest {private static class MyThread extends Thread {public void run() {for (int i = 0; i < 100; i++) {System.out.println("线程 A:"+i);}}}private static class MyRunnable implements Runnable {public void run() {for (int i = 0; i < 100; i++) {System.out.println("线程 C:"+i);}}}public static void main(String[] args) {Thread mt = new MyThread();mt.start();Thread mr = new Thread(new MyRunnable());mr.start();for (int i = 0; i < 100; i++) {System.out.println("线程 B:"+i);}}}Thread和Runnable之间的关系源码public class Thread implements Runnable {private Runnable target;public Thread(Runnable target) {init(null, target, "Thread-" + nextThreadNum(), 0);}public void run() {if (target != null) {target.run();}}}同步卖票public class TicketSeller {private static class Ticket extends Thread {private static int ticket = 1000;public void run() {while (true) {synchronized ("") {if (ticket<=0) {break;}System.out.println("卖出第"+ticket--+"张票");}}}}public static void main(String[] args) {Thread t1 = new Ticket();Thread t2 = new Ticket();t1.setName("张三");t2.setName("李四");t1.start();t2.start();}}死锁public class DeadLock {private static class Service {private Object obj1 = new Object();private Object obj2 = new Object();public void fun1() {synchronized (obj1) {System.out.println("锁定对象1");synchronized(obj2) {System.out.println("锁定对象2");}}}public void fun2() {synchronized (obj2) {System.out.println("锁定对象2");synchronized (obj1) {System.out.println("锁定对象1");}}}}public static void main(String[] args) {final Service s = new Service();for (int i = 0; i < 100; i++) {new Thread() {public void run() {s.fun1();}}.start();new Thread(new Runnable() {public void run() {s.fun2();}}).start();}}}线程间的通信 – 同步代码块public class Notify {private static class Printer {private boolean flag = false;public synchronized void print1() {while (flag) {try {this.wait();} catch (InterruptedException e) {throw new RuntimeException(e.getMessage(),e);}}System.out.println("好好学习!");flag = true;this.notify();}public synchronized void print2() {while (!flag) {try {this.wait();} catch (InterruptedException e) {throw new RuntimeException(e.getMessage(),e);}}System.out.println("天天向上!");flag = false;this.notify();}}public static void main(String[] args) {final Printer s = new Printer();new Thread() {public void run() {while (true) {s.print1();}}}.start();new Thread(new Runnable() {public void run() {while (true) {s.print2();}}}).start();}}JDK5线程间的通信 – 锁 – 互斥锁 – 同一时间只能有一个线程执行import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class NotifyByJDK5 {private static class Printer {private boolean flag = false;private ReentrantLock lock = new ReentrantLock();private Condition c1 = lock.newCondition();private Condition c2 = lock.newCondition();public void print1() {lock.lock();while (flag) {try {c1.await();} catch (InterruptedException e) {throw new RuntimeException(e.getMessage(), e);}}System.out.println("好好学习!");flag = true;c2.signal();lock.unlock();}public void print2() {lock.lock();while (!flag) {try {c2.await();} catch (InterruptedException e) {throw new RuntimeException(e.getMessage(), e);}}System.out.println("天天向上!");flag = false;c1.signal();lock.unlock();}}public static void main(String[] args) {final Printer s = new Printer();new Thread() {public void run() {while (true) {s.print1();}}}.start();new Thread(new Runnable() {public void run() {while (true) {s.print2();}}}).start();}}计时器 – 周一到周五每天凌晨四点执行程序import java.util.Calendar;import java.util.Timer;import java.util.TimerTask;public class TimerTaskDemo {private static class MyTask extends TimerTask {public void run() {int day = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);if (day==Calendar.SATURDAY || day==Calendar.SUNDAY) {return;}System.out.println("周一到周五每天凌晨4点执行");}}public static void main(String[] args) {Calendar c = Calendar.getInstance();int hour = c.get(c.HOUR_OF_DAY);if (hour>=4) {c.add(c.DATE, 1);c.set(c.HOUR_OF_DAY, 4);c.set(c.MINUTE, 0);c.set(c.SECOND, 0);}Timer timer = new Timer();timer.schedule(new MyTask(), c.getTime(), 1000*60*60*24);}}线程之间共享数据public class SharedThreadData {private static class ShareadData {private static ThreadLocal<ShareadData> threadLocal = new ThreadLocal<ShareadData>();private String name;public void setName(String name) {this.name = name;}public static ShareadData getShareadData() {ShareadData data = threadLocal.get();if (data == null) {data = new ShareadData();threadLocal.set(data);}return data;}public String toString() {return "ShareadData [name=" + name + "]";}}private static class A {public void get(){System.out.println(Thread.currentThread().getName()+" A.get Data: "+ShareadData.getShareadData());}}private static class B {public void get(){System.out.println(Thread.currentThread().getName()+" B.get Data: "+ShareadData.getShareadData());}}public static void main(String[] args) {new Thread(){public void run() {ShareadData data = ShareadData.getShareadData();data.setName("张三");System.out.println(Thread.currentThread().getName()+" set Data: "+data);new A().get();new B().get();}}.start();new Thread(){public void run() {ShareadData data = ShareadData.getShareadData();data.setName("李四");System.out.println(Thread.currentThread().getName()+" set Data: "+data);new A().get();new B().get();}}.start();}}原子类型 – 数据在操作的过程中不会执行其他线程import java.util.concurrent.atomic.AtomicInteger;public class Exercise {private static class Service {private AtomicInteger integer = new AtomicInteger();public void increment() {System.out.println(Thread.currentThread().getName()+" incr,x = "+integer.addAndGet(3));}public void decrement() {System.out.println(Thread.currentThread().getName()+" decr,x = "+integer.addAndGet(-3));}}public static void main(String[] args) {final Service service = new Service();for (int i = 0; i < 2; i++) {new Thread(){public void run() {while (true) {service.increment();}}}.start();}for (int i = 0; i < 2; i++) {new Thread(){public void run() {while (true) {service.decrement();}}}.start();}}}线程池import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ThreadPool{public static void main(String[] args) {ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); ExecutorService cachedThreadPool = Executors.newCachedThreadPool();ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);scheduledThreadPool.schedule(new Runnable() {public void run() {System.out.println("计时器线程开始");}}, 3000, TimeUnit.MILLISECONDS);for (int i = 0; i < 10; i++) {final int task = i;fixedThreadPool.execute(new Runnable() {public void run() {for (int i = 0; i < 3; i++) {System.out.println(Thread.currentThread().getName()+": 任务"+task+", 循环"+i);try {Thread.sleep(1000);} catch (Exception e) {throw new RuntimeException(e.getMessage(),e);}}}});}fixedThreadPool.shutdown();}}线程未完成,阻塞线程等待线程完成import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class ThreadPool {public static void main(String[] args) throws Exception {ExecutorService cachedThreadPool = Executors.newCachedThreadPool();final Future<String> submit = cachedThreadPool.submit(new Callable<String>() {public String call() throws Exception {System.out.println("任务开始");Thread.sleep(3000);System.out.println("任务结束");return "result";}});cachedThreadPool.execute(new Runnable() {public void run() {try {System.out.println("等待结果");System.out.println("执行成功:"+submit.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}});cachedThreadPool.shutdown();System.out.println("执行其他任务");}}批量添加任务之后获取最先完成的任务的返回结果import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorCompletionService;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPool {public static void main(String[] args) throws Exception {ExecutorService executorService = Executors.newCachedThreadPool();ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);for (int i = 0; i < 10; i++) {final int task = i;completionService.submit(new Callable<String>() {public String call() throws Exception {int ms = new Random().nextInt(3000);System.out.println("任务"+task+", 需要"+ms+"毫秒");Thread.sleep(ms);return "任务"+task+"已完成";}});}for (int i = 0; i < 10; i++) {System.out.println(completionService.take().get());}}}读取和写入锁import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class ReadWriteLockDemo {private static class PWLService {private ReadWriteLock rw = new ReentrantReadWriteLock();public void read() {rw.readLock().lock();System.out.println("读取操作");rw.readLock().unlock();}public void write() {rw.writeLock().lock();System.out.println("写入操作");rw.writeLock().unlock();}}}数据缓存 – 模拟hibernate获取元素的方法import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class CacheContainer {private ThreadLocal<Object> tl = new ThreadLocal<Object>();private ReadWriteLock rw = new ReentrantReadWriteLock();public Object get() {rw.readLock().lock();Object obj = tl.get();rw.readLock().unlock();if (obj==null) {rw.writeLock().lock();obj = tl.get();if (obj==null) {obj = new Object();tl.set(obj);}rw.writeLock().unlock();}return obj;}}同时执行线程的个数import java.util.Random;import java.util.concurrent.Semaphore;public class SemaphoreDemo {public static void main(String[] args) {final Semaphore semaphore = new Semaphore(3);for (int i = 0; i < 10; i++) {new Thread(){public void run() {try {semaphore.acquire();System.err.println(Thread.currentThread().getName()+" 开始办理业务");Thread.sleep(new Random().nextInt(3000)+1000);System.err.println(Thread.currentThread().getName()+" 业务办理结束");semaphore.release();} catch (InterruptedException e) {e.printStackTrace();}}}.start();}}}等待线程到达指定个数在继续往下执行import java.util.Random;import java.util.concurrent.CyclicBarrier;public class CyclicBarrierDemo {public static void main(String[] args) {final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);for (int i = 0; i < 3; i++) {new Thread(new Runnable() {public void run() {try {System.out.println(Thread.currentThread().getName()+": 开始爬山");Thread.sleep(new Random().nextInt(3000)+1000);System.out.println(Thread.currentThread().getName()+": 到达山顶,等待所有人");cyclicBarrier.await();System.out.println("开始下山");} catch (Exception e) {e.printStackTrace();}}}).start();}}}模拟田径赛跑 – 裁判鸣枪import java.util.Random;import java.util.concurrent.CountDownLatch;public class CountDownLatchDemo {public static void main(String[] args) {final CountDownLatch startLatch = new CountDownLatch(1);final CountDownLatch endLatch = new CountDownLatch(3);for (int i = 0; i < 3; i++) {new Thread(new Runnable() {public void run() {try {startLatch.await();System.out.println(Thread.currentThread().getName()+" 起跑,冲刺");Thread.sleep(new Random().nextInt(3000)+1000);System.out.println(Thread.currentThread().getName()+" 到达终点");endLatch.countDown();} catch (InterruptedException e) {e.printStackTrace();}}}).start();}new Thread(new Runnable() {public void run() {try {Thread.sleep(3000);System.out.println("裁判,鸣枪开始!");startLatch.countDown();endLatch.await();System.out.println("裁判,比赛结束,宣布结果!");} catch (InterruptedException e) {e.printStackTrace();}}}).start();}}线程之间交换数据 – 买卖双方约定交易地点交易import java.util.Random;import java.util.concurrent.Exchanger;public class ExchangerDemo {public static void main(String[] args) {final Exchanger<String> exchanger = new Exchanger<String>();new Thread(new Runnable() {public void run() {try {System.out.println("买家拿钱出发");Thread.sleep(new Random().nextInt(5000)+1000);System.out.println("买家到达交易地点,等待卖家");System.out.println("买家拿到了"+exchanger.exchange("钱"));} catch (Exception e) {e.printStackTrace();}}}).start();new Thread(new Runnable() {public void run() {try {System.out.println("卖家拿货出发");Thread.sleep(new Random().nextInt(5000)+1000);System.out.println("卖家到达交易地点,等待买家");System.out.println("卖家拿到了"+exchanger.exchange("货"));} catch (Exception e) {e.printStackTrace();}}}).start();}}阻塞队列import java.util.Date;import java.util.Random;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class QueueDemo {public static void main(String[] args) throws Exception {final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);for (int i = 0; i < 2; i++) {new Thread(new Runnable() {public void run() {while (true) {try {Thread.sleep(new Random().nextInt(5000)+1000);System.out.println(Thread.currentThread().getName()+": 准备获取数据, size="+queue.size());queue.take();System.out.println(Thread.currentThread().getName()+": 获取数据完毕, size="+queue.size());} catch (Exception e) {e.printStackTrace();}}}}).start();}for (int i = 0; i < 2; i++) {new Thread(new Runnable() {public void run() {while (true) {try {Thread.sleep(new Random().nextInt(1000)+1000);System.out.println(Thread.currentThread().getName()+": 准备存入数据, size="+queue.size());queue.put("data");System.out.println(Thread.currentThread().getName()+": 存入数据完毕, size="+queue.size());} catch (Exception e) {e.printStackTrace();}}}}).start();}while(true) {System.out.println(new Date());Thread.sleep(1000);}}}同步集合 – 利用动态代理实现同步集合import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.Collections;import java.util.HashMap;import java.util.Map;public class CollectionDemo {public static void main(String[] args) throws Exception {Map<String, String> map = new HashMap<String, String>();map = Collections.synchronizedMap(map);map = syncMap(map);}public static Map syncMap(final Map map) {return (Map)Proxy.newProxyInstance(CollectionDemo.class.getClassLoader(), new Class[]{Map.class},new InvocationHandler() {public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {synchronized (this) {return method.invoke(map, args);}}});}}第七章 常用类Object类finalize()垃圾回收器toString()返回该对象字符串表示equals(obj)比较两个对象是否相等System类gc()运行垃圾回收器currentTimeMillis()返回当前时间(毫秒)arraycopy(s,sP,d,dP,l)源数组复制到另一个数组getProperties()获取系统属性Thread类currentThread()当前线程getName()获取名称setName(name)设置名称sleep(millis)等待线程setDaemon(on)守护线程join()加入线程Math类PI圆周率abs(a)绝对值max(a, b)比较最大值min(a, b)比较最小值pow(a, b)n次幂sqrt(a)求平方根cbrt(a)求立方根floor(a)向下取整ceil(a)向上取整round(a)最接近的整数random()随机值String类getBytes()转换字节数组charAt(index)获取下标上的字符compareTo(obj)比较字符串endsWith(s)结尾是否包含replace(a, b)替换字符串contains(s)是否包含startsWith(p)开头是否包含concat(str)连接字符串indexOf(ch)出现的下标位置length()字符串长度split(regex)正则拆分substring(int)切割字符串toCharArray()转换为字符数组toLowerCase()转换为小写toUpperCase()转换为小写trim()忽略空格StringBuffer类append(obj)追加insert(offset, obj)插入reverse()反转字符串delete(start, end)删除Collection接口 -> ArrayList -> Vector -> LinkedList -> HashSet -> TreeSetadd(obj)添加元素size()元素数量get(index)获取元素clear()清空所有元素remove(obj)删除指定元素iterator()集合迭代Map接口 -> HashMap -> Hashtableput(key,value)添加元素get(key)根据键返回值keySet()返回所有的键entrySet()返回键值对values()返回所有的值Arrays类sort(obj[])排序binarySearch(obj[],key)二分查找copyOf(obj[],Leng)拷贝并创建一个新长度数组copyOfRange(obj[],s,e)拷贝截取创建新的数组fill(obj[],val)填充数组asList(T..)数组转成listCollections类sort(list)排序inarySearch(list,key)二分查找swap(list,i,j)交换集合中的元素synchronizedCollection使集合线程安全BigDecimal类add(augend)加法/减法remainder(divisor)取模multiply(multiplicand)乘法divide(divisor)除法File类exists()判断文件是否存在createNewFile()创建新文件getParentFile()获得文件所在的目录mkdirs()创建目录getAbsoluteFile()获取文件绝对路径getPath()获得文件参数路径getName()获得文件/文件夹名称isDirectory()判断路径是否是目录isFile()判断路径是否是文件lastModified()返回文件最后修改时间listFiles()列出所有文件delete()删除文件正则表达式字符x字符\\反斜线字符\t制表符\n换行符\r回车符\f换页符\a报警符\e转义符\c控制符字符类[abc]a,b或c[^abc]除了a,b或c[a-zA-Z]a到z或A到Z[a-d[m-p]]a到d或m到p[a-z&&[def]]d,e或f[a-z&&[^bc]]a到z,除了b和c[a-z&&[^m-p]]a到z,除了m到p预定义字符类.任何字符\d数字\D非数字\s空白字符\S非空白字符\w单词字符\W非单词字符边界匹配器^行的开头$行的结尾\b单词边界\B非单词边界\A输入的开头\G上次匹配结尾\Z输入的结尾\z输入的结尾数量词量词种类意义贪婪勉强侵占X?X??X?+一次或一次也没有X*X*?X*+零次或多次X+X+?X++一次或多次X{n}X{n}?X{n}+恰好n次X{n,}X{n,}?X{n,}+至少n次X{n,m}X{n,m}?X{n,m}+至少n次,但是不超过m次Logical运算符XYX后跟YX|YX或Y(X)X作为捕获组特殊构造(非捕获)(?:X)作为非捕获组(?idmsux-idmsux)将匹配标志idmsux(?idmsux-idmsux:X)作为带有给定标志idmsux(?=X)通过零宽度的正lookahead(?!X)通过零宽度的负lookahead(?<=X)通过零宽度的正lookbehind(?<!X)通过零宽度的负lookbehind(?>X)作为独立的非捕获组第八章 Eclipse and MyEclipse显示视图Window -> Show View -> Console || Package Explorer创建项目File -> New -> Java Project打开项目src -> Class -> Package || Name -> Finish修改字体Windows 7 -> 控制面板 -> 外观和个性化 -> 字体 -> Courier New -> 常规 -> 显示Preferences -> General -> Appearance -> Colors and Fonts -> Basic -> Text Font -> Courier New导入项目File -> Import -> Existing Projects into Workspace -> Browse || Copy projects into workspace -> Finish快捷方式Ctrl+1代码错误解决Ctrl+2,L代码返回值自动补全Alt+/代码自动补全Ctrl+Shift+O自动导入相关包Alt+↓选择代码下移Ctrl+Alt+↓复制选择行Ctrl+D删除选择行Ctrl+Alt+Enter插入空行Ctrl+/单行注释Ctrl+Alt+/,\多行注释,取消多行注释Ctrl+Shift+F格式化代码Ctrl+F11运行程序Shift+Alt+C,O,S,R,V自动生成代码Shift+Alt+Z环绕代码Shift+Alt+R重构代码Shift+Alt+M抽取方法Shift+Alt+L抽取变量F3查看源代码优化程序关闭启动项Window -> Preferences -> General -> Startup and Shutdownþ Aptana Coreþ MyEclipse QuickSetupþ MyEclipse EASIE Tomcat 6þ MyEclipse Memory Monitorþ MyEclipse Tapestry Integrationþ MyEclipse JSP Debug Toolingþ MyEclipse File Creation Wizardsþ MyEclipse Backward Compatibilityþ MyEclipse Perspective Plug-in关闭自动验证Windows -> Perferences -> Myeclipse -> Validation -> Build关闭拼写检查Windows -> Perferences -> General -> Editors -> Text Editors -> Spelling -> Enable spell checking默认Jsp编辑Window -> perferences -> General -> Editors -> File Associations -> *.jsp -> MyEclipse JSP EditorJava自动补全Windows -> Perferences -> Java -> Editor -> Content Assist -> Auto activation triggers for JavaXML打开错误Window -> perferences -> General -> Editors -> File Associations -> *.xml -> MyEclipse XML EditorBuild.xml编译错误项目 -> Perferences -> Builders -> Error -> Remove更改快捷键Window -> perferences -> General -> Keys -> Content Assist ->  Alt+/Window -> perferences -> General -> Keys -> Word Completion ->  Ctrl+Alt+/禁止Maven更新Windows -> Perferences -> Myeclipse -> Maven4Myeclipse -> Maven -> Download repository index updates on startup更改非堆内存 - eclipse.ini-XX:PermSize=512M -XX:MaxPermSize=512M关闭在线API项目 -> Perferences -> Java Build Path -> Libraries -> JRE System Library -> rt.jar -> Javadoc location -> Remove设置虚拟机的版本Window -> Perferences -> Java -> Compiler -> 6.0设置工程编译环境项目 -> Perferences -> Java Build Path -> Libraries设置JRE环境Window -> Perferences -> Java -> Installed JREs -> Add -> Next -> Directory -> Finish设置Tomcat编译环境Windows -> Perferences -> Myeclipse -> Servers -> Tomcat -> Tomcat 6.x -> JDK第九章 字符串和时间获取文件扩展名public static void main(String[] args) {String str = "文件.txt";String[] suffix = str.split("\\.");str = suffix[suffix.length-1];System.out.println(str);}查找字符串出现的位置private static void findAll(String a,String b) {int index = 0;while(true) {int find = a.indexOf(b,index);if (find==-1) {break;}System.out.println(find);index = find+1;}}判断数组中指定位置上的字节是否是中文的前一半private static boolean isCnBegin(byte[] arr,int index) {boolean flag = false;for (int i=0;i<=index;i++){flag=!flag&&arr[i]<0;}return flag;}时间import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class dateDemo {public static void main(String[] args) throws Exception {Date date = new Date();//格式化时间String pattern = "yyyy-MM-dd HH:mm:ss";DateFormat sdf = new SimpleDateFormat(pattern);String str = sdf.format(date);System.out.println(str);date = sdf.parse(str);//判断2月有多少天Calendar c = Calendar.getInstance();c.set(2013, 2, 1);c.add(c.DAY_OF_YEAR, -1);System.out.println(c.get(c.DAY_OF_MONTH));//重现开始往后100天排除周末周日c.setTime(new Date());for (int i = 1; i <= 100; i++) {int week = c.get(c.DAY_OF_WEEK);if(week==1||week==7) {i--;}c.add(c.DAY_OF_YEAR, 1);}System.out.println(c.get(c.DAY_OF_YEAR)-Calendar.getInstance().get(c.DAY_OF_YEAR));//打印时间System.out.println(c.get(c.YEAR)+"-"+(c.get(c.MONTH)+1)+"-"+c.get(c.DAY_OF_MONTH)+" "+c.get(c.HOUR_OF_DAY)+":"+c.get(c.MINUTE)+":"+c.get(c.SECOND));}}第十章 集合ArrayList<String> arrayList = new ArrayList<String>();Vector vector = new Vector();LinkedList linkedList = new LinkedList();HashSet hashSet = new HashSet();TreeSet treeSet = new TreeSet();LinkedHashSet linkedHashSet = new LinkedHashSet();HashMap hashMap = new HashMap();TreeMap treeMap = new TreeMap();Hashtable hashtable = new Hashtable();LinkedHashMap linkedHashMap = new LinkedHashMap();Properties properties = new Properties();equals() //比较对象是否相等hashCode() //比较hashCode相等compareTo() //对象进行排序自定义带泛型集合类public class MyCollection<T> {private int len = 10;private int pos = 0;private Object[] t = new Object[len];public void add(T obj) {if (pos==len) {this.len+=10;T[] newT = (T[]) new Object[this.len];for (int i = 0; i < t.length; i++) {newT[i] = (T) t[i];}this.t = newT;}t[pos++] = obj;}public T get(int index) {return (T) this.t[index];}public int size(){return pos;}}集合出列游戏import java.util.Iterator;import java.util.LinkedList;public class Game {public static void main(String[] args) {LinkedList<String> boys = new LinkedList<String>();boys.add("张三");boys.add("李四");boys.add("王五");boys.add("赵六");boys.add("孙七");int count = 0;Iterator iterator = boys.iterator();while (boys.size()>1) {count++;String boy = (String)iterator.next();if (count==3) {System.out.println("出列是:"+boy);iterator.remove();count = 0;}if (!iterator.hasNext()) {iterator = boys.iterator();}}System.out.println("幸运者:"+boys.get(0));}}统计字符串中字符出现的次数import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.Map.Entry;import java.util.Set;import java.util.TreeSet;public class CountCharNum {public static void main(String[] args) {String str = "absadsadlihsaodlsa";HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();char[] chars = str.toCharArray();for (char c : chars) {if (hashMap.containsKey(c)) {hashMap.put(c, hashMap.get(c)+1);}else{hashMap.put(c, 1);}}TreeSet treeSet = new TreeSet(new Comparator<Entry<Character, Integer>>(){public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {Character c1 = o1.getKey();Character c2 = o2.getKey();Integer v1 = o1.getValue();Integer v2 = o2.getValue();Integer num = v1-v2;return num!=0?num:c1-c2;}});Set entrySet = hashMap.entrySet();Iterator iterator = entrySet.iterator();while (iterator.hasNext()) {Entry entry = (Entry) iterator.next();treeSet.add(entry);}System.out.println(treeSet);}}第十一章 IO流递归遍历目录下的文件import java.io.File;public class dateDemo {public static void main(String[] args) throws Exception {File dir = new File("d:\\");listAllFiles(dir);}public static void listAllFiles(File dir) {File[] files = dir.listFiles();if(files!=null){for (File file : files) {if (file.isDirectory()) {listAllFiles(file);}System.out.println(file.getAbsolutePath());}}}}递归删除目录下的文件import java.io.File;public class dateDemo {public static void main(String[] args) throws Exception {File dir = new File("D:\\sss");deleteDir(dir);}public static void deleteDir(File dir) {if (dir.isDirectory()) {File[] files = dir.listFiles();if (files!=null) {for (File file : files) {deleteDir(file);}}}dir.delete();}}文件流标准关闭资源和拷贝import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class FileInputStreamDemo {public static void main(String[] args) {InputStream in = null;OutputStream out = null;try {in = new FileInputStream("a.txt");out = new FileOutputStream("b.txt");int ch;while ((ch=in.read())!=-1) {out.write(ch);}byte[] buffer = new byte[1024];int len;while ((len=in.read(buffer))!=-1) {out.write(buffer,0,len);}} catch (Exception e) {} finally {try {if(in!=null) in.close();} catch (IOException e) {}finally {try {if(out!=null) out.close();} catch (IOException e) {}}}}}实现目录的拷贝import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class FileInputStreamDemo {public static void main(String[] args) throws Exception {File source = new File("d:\\source");File target = new File("d:\\target");copyDir(source,target);}private static void copyDir(File source, File target) throws Exception {if (source.isDirectory()) {File newDir = new File(target,source.getName());newDir.mkdirs();File[] files = source.listFiles();for (File file : files) {copyDir(file, newDir);}} else {File file = new File(target, source.getName());file.createNewFile();copyFile(source,file);}}private static void copyFile(File source, File file) throws Exception {InputStream in = new FileInputStream(source);OutputStream out = new FileOutputStream(file);byte[] buffer = new byte[1024];int len;while ((len=in.read(buffer))!=-1) {out.write(buffer, 0, len);}in.close();out.close();}}复制.java文件并重新替换后缀名import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class FileInputStreamDemo {public static void main(String[] args) throws Exception {File dir = new File("d:\\");listAllJavaFiles(dir);}private static void listAllJavaFiles(File dir) throws Exception {File[] files = dir.listFiles();if (files!=null) {for (File file : files) {if (file.isDirectory()) {listAllJavaFiles(file);} else if (file.getName().endsWith(".java")) {copyFile(file);}}}}private static void copyFile(File file) throws Exception {File target = new File("c:\\jad",file.getName().replaceAll("\\.java$", ".jad"));InputStream in = new FileInputStream(file);OutputStream out = new FileOutputStream(target);byte[] buffer = new byte[1024];int len;while ((len=in.read(buffer))!=-1) {out.write(buffer, 0, len);}in.close();out.close();}}显示目录树形图import java.io.File;public class DiskTree {private static File root;public static void main(String[] args) {File dir = new File(".");root = dir;listAllFile(dir);}private static void listAllFile(File dir) {System.out.println(getSpace(dir)+dir.getName());if(dir.isDirectory()){File[] files = dir.listFiles();if(files==null) return;for (File file : files) {listAllFile(file);}}}private static String getSpace(File file) {if(file.equals(root)) return "";String space = getParentSpace(file.getParentFile());if(isLastSubFile(file)) {space += "└──";}else{space += "├──";}return space;}private static String getParentSpace(File parentFile) {if(parentFile.equals(root)) return "";String space = getParentSpace(parentFile.getParentFile());if(isLastSubFile(parentFile)){space += "    ";}else{space += "│   ";}return space;}private static boolean isLastSubFile(File file) {File[] files = file.getParentFile().listFiles();if(file.equals(files[files.length-1])){return true;}return false;}}图片分割import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class SplitImage {public static void main(String[] args) throws Exception {File file = new File("a.jpg");cutFile(file);}private static void cutFile(File file) throws Exception {int num = 1;InputStream in = new FileInputStream(file);OutputStream out = new FileOutputStream(new File("jpg/a" + num + ".jpg"));byte[] buffer = new byte[1024];int len;int count = 0;while ((len = in.read(buffer)) != -1) {if (count == 100) {out.close();out = new FileOutputStream(new File("jpg/a" + ++num + "jpg"));count = 0;}out.write(buffer, 0, len);count++;}in.close();out.close();}}缓冲流 - 比自定义缓冲数组效率低import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class BufferedStreamTest {public static void main(String[] args) throws Exception {InputStream bis = new BufferedInputStream(new FileInputStream("a.jpg"));OutputStream bos = new BufferedOutputStream(new FileOutputStream("b.jpg"));int ch;while ((ch=bis.read())!=-1) {bos.write(ch);}bis.close();bos.close();}}序列流 - 用于合并文件import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.SequenceInputStream;public class SequenceInputStreamTest {public static void main(String[] args) throws Exception {InputStream in1 = new FileInputStream("a.txt");InputStream in2 = new FileInputStream("b.txt");InputStream in = new SequenceInputStream(in1, in2);OutputStream out = new FileOutputStream("c.txt");byte[] buffer = new byte[1024];int len;while ((len=in.read(buffer))!=-1) {out.write(buffer, 0, len);}in.close();out.close();}}合并图片import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Enumeration;import java.util.Iterator;import java.util.List;public class WithPicture {public static void main(String[] args) throws Exception {List<InputStream> inList = new ArrayList<InputStream>();for (int i = 1; i <= 5; i++) {inList.add(new FileInputStream("gif/a"+i+".gif"));}final Iterator<InputStream> it = inList.iterator();InputStream in = new SequenceInputStream(new Enumeration<InputStream>() {public boolean hasMoreElements() {return it.hasNext();}public InputStream nextElement() {return it.next();}});OutputStream out = new FileOutputStream("b.gif");byte[] buffer = new byte[1024];int len;while ((len=in.read(buffer))!=-1) {out.write(buffer, 0, len);}in.close();out.close();}}对象序列化流 - 对象序列号和反序列化import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class ObjectStreamTest {public static void main(String[] args) throws Exception {ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("a.txt"));out.writeObject("aaa");out.close();ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));System.out.println(in.readObject());in.close();}}字节数组流 - 读取内存字节数组import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.util.Arrays;public class ObjectStreamTest {public static void main(String[] args) throws Exception {byte[] buffer = {1,2,3,4};ByteArrayInputStream bain = new ByteArrayInputStream(buffer);int ch;while ((ch=bain.read())!=-1) {System.out.println(ch);}ByteArrayOutputStream baout = new ByteArrayOutputStream();baout.write("hello".getBytes());baout.close();System.out.println(Arrays.toString(baout.toByteArray()));}}压缩流 - 用于zip压缩import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class ZipStreamTest {public static void main(String[] args) throws Exception {InputStream in = new FileInputStream("a.txt");ZipOutputStream zout = new ZipOutputStream(new FileOutputStream("a.zip"));zout.putNextEntry(new ZipEntry("a.txt"));byte[] buffer = new byte[1024];int len;while ((len=in.read(buffer))!=-1) {zout.write(buffer, 0, len);}in.close();zout.close();}}管道流 - 实现管道对接import java.io.PipedInputStream;import java.io.PipedOutputStream;public class PipedStreamTest {public static void main(String[] args) throws Exception {PipedInputStream pin = new PipedInputStream();PipedOutputStream pout = new PipedOutputStream();pin.connect(pout);pout.write("abcd".getBytes());byte[] buffer = new byte[1024];int len = pin.read(buffer);String result = new String(buffer, 0, len);System.out.println(result);}}字符流 - 可以实现任何字符集读取import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.Reader;import java.io.Writer;public class ReaderTest {public static void main(String[] args) throws Exception {Reader reader = new InputStreamReader(new FileInputStream("a.txt"),"UTF-8");int ch;while ((ch = reader.read()) != -1) {System.out.println((char) ch);}reader.close();Writer writer = new OutputStreamWriter(new FileOutputStream("b.txt"),"UTF-8");writer.write("中国人");writer.close();}}转换流 - 只支持本地字符集import java.io.FileReader;public class FileReaderTest {public static void main(String[] args) throws Exception {FileReader fileReader = new FileReader("a.txt");int ch = fileReader.read();System.out.println((char)ch);}}缓冲字符流import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;public class BufferedReaderTest {public static void main(String[] args) throws Exception {BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"),"UTF-8"));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("b.txt"),"GBK"));String line;while ((line=br.readLine())!=null) {bw.write(line);bw.newLine();}br.close();bw.close();}}标准输入输出流import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintStream;public class StdioStreamTest {public static void main(String[] args) throws Exception {System.setIn(new FileInputStream("a.txt"));System.setOut(new PrintStream("b.txt"));BufferedReader br = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));String line;while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();}br.close();bw.close();}}读写配置文件import java.io.FileInputStream;import java.io.PrintStream;import java.util.Properties;public class PropertiesTest {public static void main(String[] args) throws Exception {Properties props = new Properties();props.load(new FileInputStream("src/config.properties"));String username = props.getProperty("username");System.out.println(username);props.setProperty("password", "8888");props.list(new PrintStream("src/config.properties"));}}反向当行排序import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;public class ReverseSortedBySingleLine {public static void main(String[] args) throws Exception {BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"),"GBK"));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("b.txt"), "GBK"));ArrayList<String> list = new ArrayList<String>();String line;while ((line=br.readLine())!=null) {StringBuilder sb = new StringBuilder();sb.append(line);sb.reverse();list.add(sb.toString());}Collections.sort(list,new Comparator<String>() {public int compare(String s1, String s2) {int num = s1.length() - s2.length();return num!=0?num:s1.compareTo(s2);}});for (String s : list) {bw.write(s);bw.newLine();}br.close();bw.close();}}第十二章 GUI简单GUI例子 - 添加删除按钮import java.awt.Button;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class EasyGUI {public static void main(String[] args) {Frame frame = new Frame("标题");frame.setSize(800, 600);frame.setLocation(300, 100);frame.setLayout(new FlowLayout());Button btn = new Button("按钮");frame.add(btn);frame.setVisible(true);frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {e.getWindow().dispose();}});btn.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {Frame frame = (Frame) e.getComponent().getParent();Button newBtn = new Button("按钮");frame.add(newBtn);frame.setVisible(true);newBtn.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {Button btn = (Button) e.getComponent();btn.getParent().remove(btn);}});}});}}简单GUI例子 - 切换按钮import java.awt.BorderLayout;import java.awt.Button;import java.awt.Frame;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class EasyGUI {public static void main(String[] args) {final Frame frame = new Frame("标题");frame.setSize(800, 600);frame.setLocation(300, 100);final Button btn1 = new Button("按钮");final Button btn2 = new Button("按钮");frame.add(btn1,BorderLayout.NORTH);frame.add(btn2,BorderLayout.SOUTH);frame.setVisible(true);btn2.setVisible(false);frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {e.getWindow().dispose();}});btn1.addMouseListener(new MouseAdapter() {public void mouseEntered(MouseEvent e) {btn1.setVisible(false);btn2.setVisible(true);frame.setVisible(true);}});btn2.addMouseListener(new MouseAdapter() {public void mouseEntered(MouseEvent e) {btn1.setVisible(true);btn2.setVisible(false);frame.setVisible(true);}});}}简单记事本import java.awt.FileDialog;import java.awt.Frame;import java.awt.Menu;import java.awt.MenuBar;import java.awt.MenuItem;import java.awt.TextArea;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;public class Notepad {private static TextArea input = new TextArea();private static MenuBar menuBar = new MenuBar();private static Menu filemenu = new Menu("文件");private static MenuItem open = new MenuItem("打开");private static MenuItem save = new MenuItem("保存");private static MenuItem close = new MenuItem("关闭");private static class MyMenu extends Frame {public MyMenu() {this.setSize(800,600);this.setLocation(300, 100);this.setTitle("记事本");this.setVisible(true);this.add(input);filemenu.add(open);filemenu.add(save);filemenu.add(close);menuBar.add(filemenu);this.setMenuBar(menuBar);handleEvent();}private void handleEvent() {this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {closeWindow();}});close.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {closeWindow();}});open.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {openFile();}private void openFile() {FileDialog openDialog =  new FileDialog(MyMenu.this, "打开", FileDialog.LOAD);openDialog.setVisible(true);String dir = openDialog.getDirectory();String fileName = openDialog.getFile();if (dir==null||fileName==null) return;File file = new File(dir,fileName);if (!file.exists()) return;input.setText("");BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));String line;while ((line=br.readLine())!=null) {input.append(line+"\r\n");}}catch(Exception e){e.printStackTrace();}finally{if (br!=null)try {br.close();} catch (IOException e) {e.printStackTrace();}}}});save.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {saveFile();}private void saveFile() {FileDialog openDialog =  new FileDialog(MyMenu.this, "另存为", FileDialog.SAVE);openDialog.setVisible(true);String dir = openDialog.getDirectory();String fileName = openDialog.getFile();if (dir==null||fileName==null) return;File file = new File(dir,fileName);if (!file.exists()) return;String data = input.getText();OutputStream out = null;try{out = new FileOutputStream(file);out.write(data.getBytes());}catch(Exception e){e.printStackTrace();}finally{try {out.close();} catch (IOException e) {e.printStackTrace();}}}});}private void closeWindow() {this.dispose();}}public static void main(String[] args) {MyMenu menu = new MyMenu();}}资源管理器import java.awt.BorderLayout;import java.awt.Button;import java.awt.Frame;import java.awt.List;import java.awt.Panel;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.File;import java.io.IOException;public class Explorer {private static TextField input = new TextField(20);private static Button go = new Button("转到");private static Button back = new Button("后退");private static List display = new List();private static class MyWindow extends Frame {public MyWindow(){this.setSize(800,600);this.setLocation(300, 100);this.setTitle("资源管理器");this.setVisible(true);Panel p = new Panel();p.add(back);p.add(input);p.add(go);this.add(p, BorderLayout.NORTH);this.add(display, BorderLayout.CENTER);handleEvent();}private void handleEvent() {this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {closeWindow();}});go.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {openFiles();}});input.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {openFiles();}});display.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {clickItem();}private void clickItem() {String dir = input.getText();String fileName = display.getSelectedItem();if (dir==null||fileName==null) return;File file = new File(dir,fileName);if (file.isDirectory()) {input.setText(file.getAbsolutePath());openFiles();} else {try {Runtime.getRuntime().exec("cmd /c "+file.getAbsolutePath());} catch (IOException e) {e.printStackTrace();}}}});back.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {back();}private void back() {String data = input.getText();if(data=="") return;File file = new File(input.getText());File parentFile = file.getParentFile();if(parentFile==null) return;input.setText(parentFile.getAbsolutePath());openFiles();}});}private void closeWindow() {this.dispose();}private void openFiles() {String data = input.getText();File file = new File(data);if(!file.isDirectory()) return;display.removeAll();File[] files = file.listFiles();for (File f : files) {display.add(f.getName());}}}public static void main(String[] args) {MyWindow myWindow = new MyWindow();}}第十三章 网络编程UDP - 控制台聊天import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class ConsoleNetwork {public static void main(String[] args) throws Exception {new Thread(new Runnable() {public void run() {try {DatagramSocket socket = new DatagramSocket();BufferedReader br = new BufferedReader(new InputStreamReader(System.in));InetAddress address = InetAddress.getByName("127.0.0.1");while (true) {String line = br.readLine();byte[] data = line.getBytes();DatagramPacket packet = new DatagramPacket(data,data.length,address,8888);socket.send(packet);if("quit".equals(line)){break;}}socket.close();} catch (Exception e) {e.printStackTrace();}}}).start();new Thread(new Runnable() {public void run() {try {DatagramSocket socket = new DatagramSocket(8888);DatagramPacket packet = new DatagramPacket(new byte[1024],1024);while(true){socket.receive(packet);String result = new String(packet.getData(),0,packet.getLength());System.out.println("Host:"+packet.getAddress()+":"+packet.getPort()+" Data:"+result);if("quit".equals(result)){break;}}socket.close();} catch (Exception e) {e.printStackTrace();}}}).start();}}UDP - 界面聊天import java.awt.BorderLayout;import java.awt.Button;import java.awt.Dialog;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.Label;import java.awt.Panel;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.BufferedWriter;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.text.SimpleDateFormat;import java.util.Date;public class WindowNetwork {private static class MyChat extends Frame {private TextArea display = new TextArea(25,70);private TextArea dataInput = new TextArea(6,70);private TextField inInput = new TextField("127.0.0.1",20);private Button send = new Button("发 送");public MyChat() {Thread chatThread = new Thread(new Runnable() {public void run() {receiveMsg();}});chatThread.setDaemon(true);chatThread.start();this.setSize(800, 600);this.setLocation(300, 100);this.setResizable(false);this.setVisible(true);Panel panel = new Panel();panel.add(new Label("对方的ip: "));panel.add(inInput);panel.add(send);this.add(display,BorderLayout.NORTH);this.add(dataInput,BorderLayout.CENTER);this.add(panel,BorderLayout.SOUTH);this.display.setEditable(false);handleEvent();}private void handleEvent() {this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {closeWindow();}});send.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {sendMsg();}});dataInput.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {if (e.isControlDown()&&e.getKeyChar()=='\n') {sendMsg();}}});}private void closeWindow() {final Dialog okDialog = new Dialog(this);okDialog.setSize(150, 110);okDialog.setLocation(600, 300);okDialog.setLayout(new FlowLayout());okDialog.add(new Label("你确定关闭吗?"));Button ok = new Button("确定");Button cancel = new Button("取消");okDialog.add(ok);okDialog.add(cancel);okDialog.setVisible(true);ok.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {close();}});cancel.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {okDialog.dispose();}});okDialog.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {okDialog.dispose();}});}private void close() {this.dispose();}private void sendMsg() {if ("".equals(dataInput.getText())) {return;}DatagramSocket socket = null;try {socket = new DatagramSocket();InetAddress address = InetAddress.getByName(inInput.getText());byte[] data = dataInput.getText().getBytes();DatagramPacket packet = new DatagramPacket(data,data.length,address,8888);socket.send(packet);} catch (Exception e) {e.printStackTrace();}finally {if (socket!=null) {socket.close();}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String str = "本机 发送于 "+sdf.format(new Date())+"\r\n"+dataInput.getText()+"\r\n";displayMessage(str);dataInput.setText("");}}private void receiveMsg() {DatagramSocket socket = null;try {socket = new DatagramSocket(8888);DatagramPacket packet = new DatagramPacket(new byte[1024],1024);while(true){socket.receive(packet);String message = new String(packet.getData(),0,packet.getLength());String ip = packet.getAddress().getHostAddress();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String str = ip+" 发送于 "+sdf.format(new Date())+"\r\n"+message+"\r\n";displayMessage(str);}} catch (Exception e) {e.printStackTrace();}finally {if (socket!=null) {socket.close();}}}private void displayMessage(String message) {display.append(message);try {FileOutputStream file = new FileOutputStream("message.txt",true);BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(file));bw.write(message);bw.newLine();bw.close();} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) {MyChat myChat = new MyChat();}}TCP - 控制台交互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.ServerSocket;import java.net.Socket;public class TCPConsole {private static class Service implements Runnable {private Socket socket;public Service(Socket socket) {this.socket = socket;}public void run() {try {InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();out.write("welcome".getBytes());byte[] buffer = new byte[1024];String data = new String(buffer, 0, in.read(buffer));System.out.println("Send: " + data);BufferedReader br = new BufferedReader(new InputStreamReader(in));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));while (true) {String line = br.readLine();if(line==null) continue;String msg = new StringBuffer(line).reverse().toString();bw.write(msg);bw.newLine();bw.flush();if ("quit".equals(line)) {break;}}} catch (IOException e) {e.printStackTrace();}finally {try {if (socket!=null) {socket.close();}} catch (IOException e) {e.printStackTrace();}}}}private static class Client implements Runnable {public void run() {Socket socket = null;try {socket = new Socket("127.0.0.1", 7777);InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();out.write("hello".getBytes());byte[] buffer = new byte[1024];String data = new String(buffer, 0, in.read(buffer));System.out.println("receive: " + data);BufferedReader send = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));BufferedReader br = new BufferedReader(new InputStreamReader(in));while (true) {String line = send.readLine();if("".equals(line)) continue;bw.write(line);bw.newLine();bw.flush();if ("quit".equals(line)) {break;}System.out.println("data: "+br.readLine());}} catch (Exception e) {e.printStackTrace();} finally {try {if (socket!=null) {socket.close();}} catch (IOException e) {e.printStackTrace();}}}}public static void main(String[] args) throws Exception {new Thread(new Runnable() {public void run() {ServerSocket serverSocket = null;try {serverSocket = new ServerSocket(7777);while(true){Socket socket = serverSocket.accept();new Thread(new Service(socket)).start();}} catch (Exception e) {e.printStackTrace();}finally {if (serverSocket!=null) {try {serverSocket.close();} catch (IOException e) {e.printStackTrace();}}}}}).start();new Thread(new Client()).start();}}文件上传import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class Upload {private static class UploadService implements Runnable {private Socket socket;public UploadService(Socket socket) {this.socket = socket;}public void run() {try {InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();out.write("Welcome".getBytes());byte[] buffer = new byte[1024];int len = in.read(buffer);String fileName = new String(buffer,0,len);System.out.println("fileName: "+fileName);File file = new File(new File("upload"),fileName);file.createNewFile();OutputStream outFileName = new FileOutputStream(file);while ((len=in.read(buffer))!=-1) {outFileName.write(buffer, 0, len);}outFileName.close();out.write("文件上传完毕".getBytes());} catch (Exception e) {e.printStackTrace();} finally {try {if (socket!=null) {socket.close();}} catch (IOException e) {e.printStackTrace();}}}}private static class UploadClient implements Runnable {public void run() {Socket socket = null;try {socket = new Socket("127.0.0.1",7777);InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();byte[] buffer = new byte[1024];int len = in.read(buffer);String message = new String(buffer,0,len);System.out.println(message);System.out.println("请输入要上次的文件路径: ");BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String filePath = br.readLine();File file = new File(filePath);out.write(file.getName().getBytes());InputStream fileIn = new FileInputStream(file);while ((len=fileIn.read(buffer))!=-1) {out.write(buffer, 0, len);}socket.shutdownOutput();message = new String(buffer,0,in.read(buffer));System.out.println(message);socket.close();} catch (Exception e) {e.printStackTrace();} finally {try {if (socket!=null) {socket.close();}} catch (Exception e) {e.printStackTrace();}}}}public static void main(String[] args) throws Exception {new Thread(new Runnable() {public void run() {ServerSocket serverSocket = null;try {serverSocket = new ServerSocket(7777);while (true) {Socket socket = serverSocket.accept();new Thread(new UploadService(socket)).start();}} catch (IOException e) {e.printStackTrace();} finally {try {if (serverSocket!=null) {serverSocket.close();}} catch (Exception e) {e.printStackTrace();}}}}).start();new Thread(new UploadClient()).start();}}第十四章 反射和正则反射基础import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;public class RefBasic {public static void main(String[] args) throws Exception {// 1. 三种class对象Class clazz1 = Class.forName("java.lang.String");Class clazz2 = String.class;Class clazz3 = new String().getClass();System.out.println(clazz1.getName());System.out.println(clazz1.getConstructors().length);// 2. 反射构造方法Object obj = clazz1.newInstance();Constructor[] cs = clazz1.getConstructors();for (Constructor c : cs) {System.out.println(c);}Constructor c = clazz1.getConstructor(byte[].class);String hello = (String) c.newInstance("hello".getBytes());System.out.println(hello);// 3. 反射字段Field[] fs = clazz1.getDeclaredFields();for (Field f : fs) {System.out.println(f);}Field f = clazz1.getDeclaredField("hash");int modifiers = f.getModifiers();if (Modifier.isPrivate(modifiers)) {f.setAccessible(true);}f.set(hello, -1);System.out.println(hello.hashCode());// 4. 反射方法Method[] ms = clazz1.getMethods();for (Method m : ms) {System.out.println(m);}Method method = clazz1.getMethod("valueOf", char[].class);String s = (String)method.invoke(hello, new char[]{'H','E','L','L','O'});System.out.println(s);}}给对象赋值import java.lang.reflect.Field;import java.lang.reflect.Method;public class RefUtils {private static class Person {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}public static class FieldUtils {public static void setProperty(Object obj, String name, Object value) {try {Class clazz = obj.getClass();Field field = clazz.getDeclaredField(name);field.setAccessible(true);field.set(obj, value);String methodName = "set"+String.valueOf(name.charAt(0)).toUpperCase()+name.substring(1);Method method = clazz.getMethod(methodName, value.getClass());method.invoke(obj, value);} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) {Person p = new Person();FieldUtils.setProperty(p, "name", "张三");System.out.println(p.getName());}}匹配数字import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexTest {public static void main(String[] args) {String regex = "[0-9]";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher("a");System.out.println(matcher.find());}}
Java不完全教程
Java不完全教程

java不完全教程附编码示例相关推荐

  1. java中batch基础_详解Spring batch 入门学习教程(附源码)

    详解Spring batch 入门学习教程(附源码) 发布时间:2020-09-08 00:28:40 来源:脚本之家 阅读:99 作者:achuo Spring batch 是一个开源的批处理框架. ...

  2. Java异常处理教程(包含示例和最佳实践)

    异常是可能在程序执行期间发生的错误事件,它会破坏其正常流程. Java提供了一种健壮且面向对象的方式来处理异常情况,称为Java异常处理 . 我们将在本教程中研究以下主题. Java异常处理概述 异常 ...

  3. Thrift介绍以及Java中使用Thrift实现RPC示例

    场景 Thrift Thrift最初由Facebook研发,主要用于各个服务之间的RPC通信,支持跨语言,常用的语言比如C++, Java, Python,PHP, Ruby, Erlang,Perl ...

  4. 学习笔记之Java程序设计实用教程

    Java程序设计实用教程 by 朱战立 & 沈伟 学习笔记之JAVA多线程(http://www.cnblogs.com/pegasus923/p/3995855.html) 国庆休假前学习了 ...

  5. Java 8功能教程– ULTIMATE指南(PDF下载)

    编者注:在本文中,我们提供了全面的Java 8功能教程. 自Java 8公开发布以来已经有一段时间了,所有迹象都表明这是一个非常重要的版本. 我们在Java Code Geeks处提供了大量教程,例如 ...

  6. 挑战10个最难的Java面试题(附答案)【下】

    查看挑战10个最难的Java面试题(附答案)[上] 在本文中,我们将从初学者和高级别进行提问, 这对新手和具有多年 Java 开发经验的高级开发人员同样有益. 关于Java序列化的10个面试问题 大多 ...

  7. 挑战10个最难的Java面试题(附答案)【上】

    这是收集的10个最棘手的Java面试问题列表.这些问题主要来自 Java 核心部分 ,不涉及 Java EE 相关问题.你可能知道这些棘手的 Java 问题的答案,或者觉得这些不足以挑战你的 Java ...

  8. java程序设计实用教程高飞pdf_普通高等教育“计算机类专业”规划教材:Java程序设计实用教程习题集 pdf epub mobi txt 下载...

    普通高等教育"计算机类专业"规划教材:Java程序设计实用教程习题集 pdf epub mobi txt 下载 图书介绍 ☆☆☆☆☆ 高飞,赵小敏,陆佳炜 等 著 下载链接在页面底 ...

  9. 毕业设计-基于SSM框架大学教务管理平台项目开发实战教程(附源码)

    文章目录 1.项目简介 2.项目收获 3.项目技术栈 4.测试账号 5.项目部分截图 6.常见问题 毕业设计-基于SSM框架大学教务管理平台项目实战教程-附源码 课程源码下载地址:https://do ...

最新文章

  1. 传美的投40亿进军卫浴行业
  2. ios如何看idfv_iOS获取各种数据方法整理以及IDFA与IDFV使用环境
  3. [转载]漫谈游戏中的阴影技术
  4. html select选择事件_用 Java 拿下 HTML 分分钟写个小爬虫
  5. 从“卡脖子”到“主导”,国产数据库 40 年的演变!
  6. 剑指offer二:替换空格
  7. SOA架构设计的案例分析
  8. 数字电子技术逻辑运算
  9. 软件单元测试方法,单元测试的基本测试方法
  10. 电动汽车对系统运行的影响(Matlab实现)
  11. 黑苹果AppleStore不能下载应用
  12. 揭秘跨境电商亚马逊测评的培训骗局!千万不要上当受骗!
  13. 怎么把avi文件转换成mp4视频格式,4个高能方法
  14. ECCV2018 papers
  15. 项目中的用户鉴权是如何实现的?
  16. 超声成像_人工智能如何帮助转变医学超声成像
  17. 张超 计算机 清华 论文,张超-清华大学航天航空学院
  18. 微信公众号开发前端逻辑
  19. 连接ARM设备的两种方式
  20. webgl-原生纹理贴图

热门文章

  1. 【运筹学】对偶理论总结 ( 对称性质 | 弱对偶定理 | 最优性定理 | 强对偶性 | 互补松弛定理 ) ★★★
  2. 分布式任务调度系统设计:详解Go实现任务编排与工作流
  3. Intellij IDEA 10.5 语言设置
  4. 【智力题】小环绕大环
  5. 轨迹绕圈算法_基于三次B样条曲线拟合的智能车轨迹跟踪算法
  6. 2/8法则系列 | 你真的了解二八法则吗?
  7. 营销革命4.0 从传统到数字
  8. mysql 设置的黑名单_在SQL中实现多条件任意组合黑名单的方法
  9. ECharts+高德卫星地图-飞线图效果
  10. 计算机睡眠和休眠哪个更好,windows7睡眠与休眠的区别_win7电脑休眠和睡眠哪个好...