java不完全教程附编码示例

Java不完全教程

第一章Java预备知识

常用DOS命令

help,dir,md,cd,rd,del,copy,move,start,type,cls,attrib

配置环境变量

JAVA_HOME C:\soft\Java\jdk1.6.0_37

Path %JAVA_HOME%\bin

第一个程序

public class Hello {

public static void main(String[] args) {

System.out.println("Hello");

}

}

Java三种注释

文档注释 /***/

多行注释 /**/

单行注释 //

启动记事本程序 - DEMO

public 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 -> TreeSet

add(obj)

添加元素

size()

元素数量

get(index)

获取元素

clear()

清空所有元素

remove(obj)

删除指定元素

iterator()

集合迭代

Map接口 -> HashMap -> Hashtable

put(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..)

数组转成list

Collections类

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运算符

XY

X后跟Y

X|Y

X或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 Editor

Java自动补全

Windows -> Perferences -> Java -> Editor -> Content Assist -> Auto activation triggers for Java

XML打开错误

Window -> perferences -> General -> Editors -> File Associations -> *.xml -> MyEclipse XML Editor

Build.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不完全教程


猜你喜欢

转载自blog.csdn.net/shuryuu/article/details/80597340