Java API--接口

1. java.lang

java.lang包会自动导入

1.1Object类

是类层次结构的根类,每个类都是以object作为超类

1.1.1方法简介
类型方法名备注
protected Objectedclone()创建并返回此对象的一个副本。
booleanequals()指示其他某个对象是否与此对象“相等”。
protected voidfinalize()当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。
Class<?>getClass()返回此 Object 的运行时类。
inthashCode()返回此对象的哈希码值
voidnotify()唤醒在此对象监视器上等待的单个线程。
voidnotifyAll()返回在此对象监视器上等待的所有线程。
StringtoString()返回该对象的字符串表示。
voidwait()在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。
voidwait(long timeout)在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。
voidwait(long timeout,int nanos)在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者其他某个线程中断当前线程,或者已超过某个实际时间量前,导致当前线程等待。
1.1.2toString()
package Again;

public class ObjecttoString {
	public static void main(String[] args) {
		Person person=new Person("Bob",19,88.99);
		System.out.println(person.getName()+" "+person.getAge()+" "+person.getScore());
		//System.out.println(person);//Again.Person@5caf905d若不重写toString()方法
		System.out.println(person);//重写toString方法后,显示[name=Bob,age=19,score=88.99]
	}
}
class Person{
	public Person() {}
	public Person(String name,int age,double score) {
		this.age=age;
		this.name=name;
		this.score=score;
	}
	private String name;
	private int age;
	private double score;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		//return super.toString();
		return "[name="+name+",age="+age+",score="+score+"]";
	}
}
1.1.3equals()
package Again;

public class ObjectEquals {
	public static void main(String[] args) {
		int i1=10;
		int i2=10;
		int i3=12;
		//==基础类型按值比较
		System.out.println(i1==i2);
		System.out.println(i1==i3);
		//当前对象和参数对象比较大小,默认是比较内存地址,如果要比较对象的属性,可以重写该方法。
		person p1=new person("Bob",19,88.98);
		person p2=new person("Bob",19,88.98);
		//对象为引用类型时,都按地址值比较
		System.out.println(p1==p2);//false
		System.out.println(p1.equals(p2));//没有重写equals:false.重写equals之后返回属性值		
	}
}
class person extends Object{
	public person() {}
	public person(String name,int age,double score) {
		this.age=age;
		this.name=name;
		this.score=score;
	}
	private String name;
	private int age;
	private double score;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	@Override
	//方法重写不能改变参数属性
	public boolean equals(Object obj) {
		//向下转型,转成person才能访问其特有属性。
		person Obj=(person)obj;
		if(this.name==Obj.name&&this.age==Obj.age&&this.score==Obj.score)return true;
		else return false;
	}
	
}
1.1.4hashCode()
package Again;

public class ObjectHashcode {
	public static void main(String[] args) {
		Integer a=1;
		Integer b=a;
		System.out.println(a.hashCode());
		System.out.println(a==b);//true
		System.out.println(a.equals(b));//true
	}
}
1.2String

String 类代表字符串。字符串是常量;它们的值在创建之后不能更改。 如果是第一次使用字符串,java会在字符串常量池创建一个对象。 再次使用相同的内容时,会直接访问常量池中存在的对象。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。字符串串联符号("+")提供将其他对象转换为字符串的特殊支持。字符串串联是通过 StringBuilder(或 StringBuffer)类及其 append 方法实现的。字符串转换是通过 toString 方法实现的。

package Again;

public class APIString {
	public static void main(String[] args) {
		//创建String对象
		String a=new String();//调用无参构造方法,使其表示一个空字符序列
		a="asdasdw";
		byte[] s= {97,98,99};
		String d=new String(s);
		System.out.println(d);//abc   通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
		String A="asdasDw";
		System.out.println(a.charAt(2));//a[2]的值
		System.out.println(a.codePointAt(0));//返回指定索引处的字符(Unicode 代码点)。
		System.out.println(a.codePointBefore(1));// 返回指定索引之前的字符(Unicode 代码点)。
		System.out.println(a.codePointCount(1, 3)); //返回此 String 的指定文本范围中的 Unicode 代码点数。
		System.out.println(a.compareTo(A));//按字典顺序比较两个字符串。
		System.out.println(a.compareToIgnoreCase(A));//按字典顺序比较两个字符串,不考虑大小写。
		System.out.println(a.concat(A));//将指定字符串连接到此字符串的结尾。
		System.out.println(a.contains(A));//当且仅当此字符串包含指定的 char 值序列时,返回 true。
		System.out.println(a.contentEquals(A));//将此字符串与指定的 CharSequence 比较。当且仅当此 String 与指定序列表示相同的 char 值序列时,结果才为 true。 
		//将此字符串与指定的 StringBuffer 比较。当且仅当此 String 与指定 StringBuffer 表示相同的字符序列时,结果才为 true。 
	//	System.out.println(a.contentEquals(sb));
		char[] w= {'d','n'};
		//静态方法直接用类名调用才不会警告
 		System.out.println(String.copyValueOf(w));// 返回指定数组中表示该字符序列的 String。 return new String(w);
 		System.out.println(String.copyValueOf(w, 0, 2));//data - 字符数组。offset - 子数组的初始偏移量。count - 子数组的长度。 
 		System.out.println(a.endsWith("dw"));//测试此字符串是否以指定的后缀结束。
 		System.out.println(a.equals(a));// 将此字符串与指定的对象比较。引用类型默认比较的是地址值
 		System.out.println(A.equalsIgnoreCase(a));// 将此 String 与另一个 String 比较,不考虑大小写。
 //		System.out.println(a.format(format, args));
 //		System.out.println(A.getBytes());//使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
 //		a.getChars(0, 2, w, 1);
 //		System.out.println(w);
 		System.out.println(a.hashCode());
 		System.out.println(a.indexOf("da"));//返回指定字符在此字符串中第一次出现处的索引。
 		System.out.println(a.indexOf("da", 2));// 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。返回的整数是满足下式的最小 k 值: 
 	    // k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
 		System.out.println(a.intern());//返回字符串对象的规范化表示形式。
 		System.out.println(a.isEmpty());//当且仅当 length() 为 0 时返回 true。
 		System.out.println(a.lastIndexOf("s"));
 		System.out.println(a.lastIndexOf("s",3));//返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
 		System.out.println(a.lastIndexOf("as"));//返回指定子字符串在此字符串中最右边出现处的索引
 //		System.out.println(a.lastIndexOf(9798));//  return lastIndexOf(ch, length() - 1);
 		System.out.println(a.length());//返回此字符串的长度
 //		System.out.println(a.matches());// 告知此字符串是否匹配给定的正则表达式。
 		System.out.println(a.offsetByCodePoints(2, 1));//返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。
 		System.out.println(a.regionMatches(0,A , 0, 3));//a从0位置开始与A从0位置开始比较,比较长度为3
 		System.out.println(a.replace('s', 'h'));//用 newChar 替换此字符串中出现的所有 oldChar 得到的。
 		System.out.println(a.replaceAll("as", "ww"));//使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
 		System.out.println(a.replaceFirst("as", "QQ"));// 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
 //		System.out.println(a.split("w"));// 根据给定正则表达式的匹配拆分此字符串。
 //		System.out.println(a.split(regex, limit));
 		System.out.println(a.startsWith("as"));//测试此字符串是否以指定的前缀开始。
 		System.out.println(a.startsWith("da",2 ));//测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
 		System.out.println(a.substring(2));//从a[2]开始直到结束的字串
 		System.out.println(a.substring(2, 4));//返回从a[2]开始到a[4]结束
 		System.out.println(a.toCharArray());//将此字符串转换为一个新的字符数组。
 		System.out.println(A.toString());//返回字符串对象本身
 		System.out.println(A.toLowerCase());//所有字符都转换为小写
 		System.out.println(A.toUpperCase());//所有字符都转换为大写
 //		System.out.println(A.toUpperCase(locale));
 		System.out.println(A.trim());//忽略前导空白和尾部空白
 		System.out.println(String.valueOf(99));
	}
}
1.3StringBuilder/StringBuffer
  • public final class **StringBuilder**

  • 封装了char[]数组,一个可变的字符序列。内部字符数组默认初始容量是16.如果大于16会尝试将扩容,新数组大小原来的变成2倍+2,容量如果还不够,直接扩充到需要的容量大小。

  • 1、 在线程安全上,

    –StringBuffer是旧版本就提供的,线程安全的。@since JDK1.0

    –StringBuilder是jdk1.5后产生,线程不安全的。@since 1.5

    2、 在执行效率上,StringBuilder > StringBuffer > String

    3、 源码体现:本质上都是在调用父类抽象类AbstractStringBuilder来干活,只不过Buffer把代码加了同步关键字,使得程序可以保证线程安全问题。

  • package Again;
    
    import java.net.StandardSocketOptions;
    
    public class APIStringBuilder {
    	public static void main(String[] args) {
    		String s="fhksdhkfalshkflaksjlsduf";
    		StringBuilder SB1=new StringBuilder();//构造一个不带任何字符的字符串生成器,其初始容量为 16 个字符。
    //		StringBuilder SB2=new (CharSequence seq);// 构造一个字符串生成器,它包含与指定的 CharSequence 相同的字符。
    		StringBuilder SB3=new StringBuilder(20);//构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。
    		StringBuilder SB4=new StringBuilder("sasa");
    		System.out.println(SB1.append(23));//参数的字符串表示形式追加到序列
    		System.out.println(SB3.capacity());//返回当前容量。
    		System.out.println(SB4.charAt(2));// 返回此序列中指定索引处的 char 值。
    		System.out.println(SB4.codePointAt(2));//返回指定索引处的字符(统一代码点)。unicode编号
    		System.out.println(SB4.codePointBefore(2));//返回指定索引处前一个字符(统一代码点)。unicode编号
    		System.out.println(SB4.codePointCount(1, 3));//return endIndex - beginIndex;
    		System.out.println(SB4.delete(2, 3));//从a[2]开始删除直到a[4]
    		System.out.println(SB4.deleteCharAt(1));//删除指定位置的字符
    //		ensureCapacity(int minimumCapacity) 确保容量至少等于指定的最小值
    		//char[] w=new char[10];
    		char[] w= {'Q','Q','Q','Q','Q','Q'};
    		SB4.getChars(1, 2, w, 0);//获取SB4里[[1,2)里的值给w
    		System.out.println(w);
    		SB4.append("fhkjfshdfkjsdhkfklafhaf");
    		System.out.println(SB4);
    		System.out.println(SB4.indexOf("hk"));//返回第一次出现的指定子字符串在该字符串中的索引。
    		System.out.println(SB4.indexOf("hk",3));//从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。
    		System.out.println(SB4.insert(3, "DDD"));//将 参数的字符串表示形式插入此序列中。
    		System.out.println(SB4.insert(2, w, 0, 4));//将指定的子序列插入此序列中。
    		System.out.println(SB4.lastIndexOf("f"));// 返回最右边出现的指定子字符串在此字符串中的索引。
    		System.out.println(SB4.lastIndexOf("f", 6));// 返回最右边出现的指定子字符串在此字符串中的索引。搜索开始处的索引。
    		System.out.println(SB4.offsetByCodePoints(3, 2));//3向后偏倚2
    		System.out.println(SB4.replace(0, 3, "wang"));//wang代替[0,3)
    		System.out.println(SB4.reverse());//字符串反转,第一个成为最后一个
    		SB4.setCharAt(0, 'O');//a[0]替换成字符o
    		System.out.println(SB4);
    		SB4.setLength(4);//设置字符序列的长度。
    		System.out.println(SB4);
    		System.out.println(SB4.substring(2));//从a[0]开始向后截取字符串,返回一个新的String
    		System.out.println(SB4);
    		System.out.println(SB4.substring(0, 2));//[0,2)截取字符串,返回一个新的String
    		SB4.trimToSize();//尝试减少用于字符序列的存储空间。
    	}
    }
    
    
1.4包装类

基本类型 byte short int long float double boolean char
包装类型 Byte Short Integer Long Float Double Boolean Character

Integer
package Again;

public class APINumber {
	public static void main(String[] args) {
		//静态属性
		System.out.println(Integer.MAX_VALUE);// int 类型能够表示的最大值。
		System.out.println(Integer.MIN_VALUE);//int 类型能够表示的最小值。
		System.out.println(Integer.SIZE);//以二进制补码形式表示 int 值的比特位数
		System.out.println(Integer.TYPE);// 表示基本类型 int 的 Class 实例
		//构造方法  Integer(int value) 
		Integer I1=new Integer(52);
		System.out.println(I1);
		Integer I2=new Integer("52");
		System.out.println(I2);//55
		System.out.println(Integer.bitCount(127));//返回指定 int 值的二进制补码表示形式的 1 位的数量。
		System.out.println(I1.byteValue());// 以 byte 类型返回该 Integer 的值。超过127从0开始计数
		System.out.println(I1.compareTo(I2));//在数字上比较两个 Integer 对象。I1>I2返回1,相等返回0,否则返回-;
		System.out.println(Integer.decode("3222")+1);// 将 String 解码为 Integer。
	//	System.out.println(Integer.getInteger(String));//确定具有指定名称的系统属性的整数值。
		System.out.println(Integer.highestOneBit(128));//二进制码,数值为1的最高位
		System.out.println(Integer.lowestOneBit(127));//二进制码,数值为1的最低位
		System.out.println(Integer.numberOfLeadingZeros(128));//在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前,返回零位的数量。
		System.out.println(Integer.numberOfTrailingZeros(128));// 返回指定的 int 值的二进制补码表示形式中最低(“最右边”)的为 1 的位后面的零位个数。
		System.out.println(Integer.parseInt("128")+1);// 将字符串参数作为有符号的十进制整数进行解析。
		System.out.println(Integer.parseInt("1111111", 2));//1111111为2机制数
		System.out.println(Integer.reverse(128));//返回通过反转指定 int 值的二进制补码表示形式中位的顺序而获得的值。
		System.out.println(Integer.toBinaryString(128));//以二进制(基数 2)无符号整数形式返回一个整数参数的字符串表示形式。
		System.out.println(Integer.toHexString(128));// 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式。
		System.out.println(Integer.toOctalString(128));// 以八进制(基数 8)无符号整数形式返回一个整数参数的字符串表示形式。
	}
}

2. java.util

2.1日期

从1970-1-1 0点开始的毫秒值。

package Again;

import java.util.Date;

public class UtilDate {
	public static void main(String[] args) {
		Date date1=new Date();
		Date date2=new Date(2020,4,25);
		Date date3=new Date(2020,4,25,15,15);
		Date date4=new Date(900000000000L);//封装指定的时间点
		Date date5=new Date("900000000000");
		System.out.println(date2.equals(date3));
		System.out.println(date2.getDate());
	//	System.out.println(date2.getDay());
		System.out.println(date2.getMonth());
		System.out.println(date2.after(date3));//false
		System.out.println(date2.before(date3));//true
		System.out.println(date3.getHours());
		System.out.println(date3.getMinutes());
		System.out.println(date3.getTime());//其他单位都换成秒
		System.out.println(date3.getTimezoneOffset());
	//	System.out.println(Date.parse("2020425"));
		date1.setYear(2020);
		date1.setMonth(7);
		date1.setDate(25);
		System.out.println(date1);
		System.out.println(date1.getYear());
		
	}
}
2.2SimpleDateFormat日期工具

一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。很多方法不常用,常与Date连用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TOQ62zko-1588845358416)(C:\Users\wang\Desktop\image-20200425165229695.png)]

package Again;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ObjectSingleDate {
	public static void main(String[] args) {
		//用来把String类型的日期   和  Date类型的日期  互转
		SimpleDateFormat Si1=new SimpleDateFormat();
		String da="19970209";
		SimpleDateFormat Si2=new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d=Si2.parse("1998-02-21");//转化成Si2格式的日期
			System.out.println(d.getDate());
			System.out.println(Si2.toPattern());//yyyy-MM-dd 返回描述此日期格式的模式字符串。
		//	Si2.applyPattern(da);
			System.out.println(da);
			System.out.println(Si2.format(d)+909);//将Date类型的日期,转成 字符串类型
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3. java.math

3.1BigDecimal

BigDecimal用来解决java中浮点数运算不精确的现象。

package Again;

import java.math.BigDecimal;

public class API_BigDecimalBigInteger {
	public static void main(String[] args) {
		BigDecimal b=new BigDecimal("898989898.91211");
		BigDecimal a=new BigDecimal("2121.21211");
		System.out.println(b.abs());
//		System.out.println(b.abs(BigDecimal.ROUND_HALF_UP));
		System.out.println(b.add(a));
		System.out.println(b.doubleValue());//转化为double,其他类型也可以转
//		System.out.println(b.divide(a));
		System.out.println(b.max(a));//a,b中大的一个
		System.out.println(b.min(a));//a,b中小的一个
		System.out.println(b.movePointLeft(2));//左移小数点两位
		System.out.println(b.movePointRight(2));//右移小数点两位
		System.out.println(b.multiply(a));
		BigDecimal c=b.divide(a,3,BigDecimal.ROUND_HALF_UP);
		System.out.println(c);//b/a四舍五入,保留三位小数
		System.out.println(b.divide(a,BigDecimal.ROUND_HALF_UP));
	//	System.out.println(b.multiply(a,BigDecimal.ROUND_HALF_UP));
		System.out.println(b.subtract(a));//b-a
		System.out.println(b.toBigInteger());//转化大整数
	}
}

3.2BigInteger
package Again;

import java.math.BigInteger;

public class APIBigInteger {
	public static void main(String[] args) {
		BigInteger a=new BigInteger("7");
		BigInteger b=new BigInteger("9");
		System.out.println(b.abs());
		System.out.println(a.add(b));
		System.out.println(a.and(b));//两个同时为1,结果为1,否则为0
		System.out.println(a.bitCount());//返回此 BigInteger 的二进制补码表示形式中与符号不同的位的数量。
		System.out.println(a.bitLength());//返回此 BigInteger 的最小的二进制补码表示形式的位数,不包括 符号位。
		System.out.println(a.divide(b));//舍去小数部分
		System.out.println(a.gcd(b));//最大公约数
		System.out.println(a.isProbablePrime(100));//素数计算的范围是3
		System.out.println(a.multiply(b));
		System.out.println(a.or(b));
		System.out.println(b.pow(2));//b的2次方
		System.out.println(b.shiftLeft(3));//b*2^3
		System.out.println(b.shiftRight(2));//b/2^2
		System.out.println(b.subtract(a));//b-a
	}
}

4. java.io(Object)

in/out相对于程序而言的输入(读取)和输出(写出)的过程

字节流:针对二进制文件
InputStream --FileInputStream --BufferedInputStream --ObjectInputStream
OutputStream --FileOutputStream --BufferedOutputStream -ObjectOutputStream

​ InputStream:是字节流 读取流的父类 。是抽象类,不能创建对象,只能学习共性方法字符流:针对文本文件。读写容易发生乱码现象,在读写时最好指定编码集为utf-8

​ FileInputStream:子类,继承了父类的方法,就不重复学父类的方法了。直接学习创建对象就行
​ BufferedInputStream:子类,继承了父类的方法,就不重复学父类的方法了。直接学习创建对象就行
​ Reader --BufferedReader --InputStreamReader --PrintWriter/PrintStream
​ Writer --BufferedWriter --OutputStreamWriter

​ Reader 是字符流读取流的父类。是抽象类,不能创建对象,所以只能学共性方法.

​ FileReader子类,继承了父类的共性方法,直接学子类创建对象
​ BufferedReader子类,继承了父类的共性方法,直接学子类创建对象

4.1File
package Again;

import java.io.File;
import java.io.IOException;

public class APIFile {
	public static void main(String[] args) throws IOException {
		File cs1=new File("D:\\hah\\day01.txt");
		File cs2=new File("D:\\hah","ww.txt");
		File cs3=new File("D:\\hah","w.txt");
		File cs4=new File("D:\\hah");
		System.out.println(cs1.canRead());//文件是否可读
		System.out.println(cs2.canWrite());//文件是否可写
		cs2.createNewFile();//当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
		System.out.println(cs2.canRead());
		cs2.delete();//删除此抽象路径名表示的文件或目录。
		System.out.println(cs1.getAbsolutePath().toString());//返回此抽象路径名的绝对路径名形式。
		System.out.println(cs3.getName());
		System.out.println(cs3.getParent());
		System.out.println(cs3.isAbsolute());//测试此抽象路径名是否为绝对路径名。
		System.out.println(cs3.isDirectory());// 测试此抽象路径名表示的文件是否是一个目录。
		System.out.println(cs3.isFile());//测试此抽象路径名表示的文件是否是一个标准文件。
		System.out.println(cs3.isHidden());//    测试此抽象路径名指定的文件是否是一个隐藏文件。
		System.out.println(cs1.lastModified());//返回此抽象路径名表示的文件最后一次被修改的时间。
		System.out.println(cs1.length());//返回由此抽象路径名表示的文件的长度。
		System.out.println(File.listRoots());// 列出可用的文件系统根。
//		cs4.mkdir();//创建此抽象路径名指定的目录。
		cs2.renameTo(cs3);//重新命名此抽象路径名表示的文件。
	}
}

4.3字节流读取
inputStream
package Again;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class APIInputStream {
	public static void main(String[] args) {
		method1();
		System.out.println("==========================================");
		method2();
		System.out.println("==========================================");
		//method3();
	}
	private static void method2() {
		// TODO Auto-generated method stub
		InputStream a=null;
		try {
			a=new BufferedInputStream(new FileInputStream("D:\\hah\\day14.txt"));
			int b=0;
			try {
				while((b=a.read())!=-1) {
					System.out.println(b);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static void method1() {
		// TODO Auto-generated method stub
		InputStream a=null;
		try {
			a=new FileInputStream(new File("D:\\hah\\day01.txt"));
			int b=0;
			try {
				while((b=a.read())!=-1) {
					System.out.println(b);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

outputStream
package Again;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class APIOutpputStream {
	public static void main(String[] args) {
		method1();
		method2();
	}

	private static void method2() {
		// TODO Auto-generated method stub
		OutputStream a=null;
		try {
			a=new FileOutputStream("D:\\hah\\day01.txt");
			try {
				a.write(97);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private static void method1() {
		// TODO Auto-generated method stub
		OutputStream a=null;
		try {
			a=new BufferedOutputStream(new FileOutputStream("D:\\hah\\day01.txt"));
			try {
				a.write(97);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

4.4字符流读取
Reader
package Again;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class APIReader {
	public static void main(String[] args) {
		method1();
		System.out.println("==============================");
		method2();
	}

	private static void method2() {
		// TODO Auto-generated method stub
		Reader a=null;
		try {
			
			a=new FileReader("D:\\hah\\day01.txt");
			int b=0;
			try {
				while((b=a.read())!=-1) {
					System.out.println(b);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static void method1() {
		// TODO Auto-generated method stub
		Reader a=null;
		try {
			
			a=new BufferedReader(new FileReader("D:\\hah\\day01.txt"));
			int b=0;
			try {
				while((b=a.read())!=-1) {
					System.out.println(b);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
	
Writer
package Again;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class APIWriter {
	public static void main(String[] args) {
		method1();
		System.out.println("=============================");
		method2();
		System.out.println("==============================");
	}

	private static void method2() {
		// TODO Auto-generated method stub
		Writer a=null;
		try {
			a=new FileWriter("D:\\hah\\day01.txt");
			a.write("wangjingxiaokeai");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private static void method1() {
		// TODO Auto-generated method stub
		Writer a=null;
		try {
			a=new BufferedWriter(new FileWriter("D:\\hah\\day01.txt"));
			a.write("wangjingxiaokeai");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
复制文件
package Again;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class APICopyFile {
	public static void main(String[] args) {
		method1();
		method2();
	}

	private static void method1(){
		// TODO Auto-generated method stub
		InputStream a=null;
		OutputStream b=null;
		try {
			a=new BufferedInputStream(new FileInputStream("D:\\hah\\1.png"));
			b=new BufferedOutputStream(new FileOutputStream("D:\\hah\\wang.png"));
			int c=0;
			while((c=a.read())!=-1) {
				b.write(c);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
				b.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private static void method2() {
		// TODO Auto-generated method stub
		Reader a=null;
		Writer b=null;
		try {
			a=new BufferedReader(new FileReader("D:\\hah\\day14.txt"));
			b=new BufferedWriter(new FileWriter("D:\\hah\\wan.txt"));
			int c=0;
			while((c=a.read())!=-1) {
				b.write(c);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
				b.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}
4.5序列化反序列化

-序列化:是指把java程序中的对象,永久存储到磁盘的过程。–out
–ObjectOutputStream
–ObjectOutputStream(OutputStream out)
–void writeObject(Object obj)
将指定的对象写入 ObjectOutputStream。

-反序列化:是指把磁盘中的已经 序列化好的文件 恢复到 java程序中来。-- in
–ObjectInputStream
–ObjectInputStream(InputStream out)
–Object readObject()

package Again;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class APIObjectStream {
	public static void main(String[] args) {
		method1();//序列化
		method2();//反序列化
	}

	private static void method1() {
		// TODO Auto-generated method stub
		ObjectOutputStream a=null;
		try {
			Student s=new Student("Bob",20);
			a=new ObjectOutputStream(new FileOutputStream("D:\\hah\\day01.txt"));
			a.writeObject(s);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static void method2() {
		// TODO Auto-generated method stub
		ObjectInputStream a=null;
		try {
			a=new ObjectInputStream(new FileInputStream("D:\\hah\\day01.txt"));
			try {
				Object b=a.readObject();
				System.out.println(b.toString());
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				a.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
//如果想要序列化,必须先实现序列话接口
class Student implements Serializable{
	//实现序列化接口后,要生成唯一的版本id值作为文件的标志
	private static final long serialversionUID=1L;
	public Student() {};
	public Student(String name,int age) {
		this.name=name;
		this.age=age;
	}
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		//return super.toString();
		return "Student [name]="+name+", age="+age+"]";
	}
}
4.6编码转化流

专门用来解决 ,字符流 读写乱码现象。

OutputStreamWriter:转换流,把字节输出流 转成 字符 输出流

InputStreamReader:转换流,把字节读取流 转成 字符 读取流

package Again;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class APIExchangeStream {
	public static void main(String[] args) {
		OutputStream a=null;
		try {
			//创建字节流
			a=new FileOutputStream("D:\\hah\\day14.txt");
			//字节输出流转化成字符输出流
			Writer b=new OutputStreamWriter(a,"gbk");
			b.write("I Love You");
			b.flush();//必须要刷出缓存中的数据到文件里
			System.out.println("+++++++++++++++++++++++++");
			InputStream c=new FileInputStream("D:\\hah\\day01.txt");
			BufferedReader d=new BufferedReader(new InputStreamReader(new FileInputStream("D:\\hah\\day01.txt")));
			System.out.println(d.read());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

5. 集合

5.1泛型

标志是<> ,通常配合集合一起使用,编译时类型检查.

E - Element (在集合中使用,因为集合中存放的是元素)

T - Type(Java 类)

K - Key(键)

V - Value(值)

N - Number(数值类型)

? - 表示不确定的java类型

5.2Collection

存放对象的数据结构。其中长度可变,而且集合中可以存放不同类型的对象。并提供了一组操作成批对象的方法。

5.5list

1、 数据有序

2、 允许存放重复元素

3、 元素都有索引

ArrayList
  1. 存在于java.util包中。

  2. 内部用数组存放数据,封装了数组的操作,每个对象都有下标。

  3. 内部数组默认初始容量是10。如果不够会以1.5倍容量增长。

  4. 查询快,增删数据效率会降低。

package Again;

import java.util.ArrayList;
import java.util.ListIterator;

public class APIList {
	public static void main(String[] args) {
		ArrayList<String> a=new ArrayList();
		System.out.println(a.add("sass"));
		System.out.println(a.add("hahahah"));
		a.add("xiongda");
		a.add("xionger");
		a.add("guangtouq");
		a.add("xionger");
		a.add("guangtouq");
		System.out.println(a.contains("sass"));
		System.out.println(a.get(1));//返回此列表中指定位置上的元素。
		System.out.println(a.indexOf("sass"));//  返回此列表中首次出现的指定元素的索引,
		System.out.println(a.isEmpty());//如果此列表中没有元素,则返回 true
		System.out.println(a.remove(0));
		for(int i=0;i<a.size(); i++) {
			System.out.println("**"+a.get(i));
		}
		for(String i:a) {
			System.out.println(i);
		}
		ListIterator<String> i = a.listIterator();
		while(i.hasNext()) {
			System.out.println("@"+i.next());
		}
	}
}
LinkedList

双向链表,两端效率高。底层就是数组和链表实现的。

package Again;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;

public class APIList {
	public static void main(String[] args) {
		method2();
	}

	private static void method2() {
		// TODO Auto-generated method stub
		LinkedList a=new LinkedList();
		a.add("sass");
		a.add("hahahah");
		a.add("xiongda");
		a.add("xionger");
		a.add("guangtouq");
		a.add("xionger");
		a.add("guangtouq");
		System.out.println(a);
		a.addLast("Coco");
		System.out.println(a.getLast());
		a.addFirst("wang");
		System.out.println(a.getFirst());
		System.out.println(a);
		System.out.println(a.element());//获取但不移除此列表的头(第一个元素)。
		a.pop();//从此列表所表示的堆栈处弹出一个元素。
		a.push("Tom");
		System.out.println(a.getLast());
	}
5.6Set

一个不包含重复元素的 collection。

数据无序(因为set集合没有下标)。

由于集合中的元素不可以重复。常用于给数据去重。

HashSet

底层是哈希表,包装了HashMap,相当于向HashSet中存入数据时,会把数据作为K,存入内部的HashMap中。当然K仍然不许重复。

package Again;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class APIHashSet {
	public static void main(String[] args) {
		Set<Integer> set=new HashSet<>();
		set.add(99);
		set.add(99);
		set.add(98);
		set.add(95);
		set.add(91);
		System.out.println(set);//无重复元素
		set.remove(99);
		Iterator it=set.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
}
TreeSet

底层就是TreeMap,也是红黑树的形式,便于查找数据。

5.7Map

将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。
一些映射实现则不保证顺序。可以根据键 提取对应的值,存放的都是无序数据,初始容量是16,默认的加载因子是0.75

HashMap

HashMap的键要同时重写hashCode()和equals()

hashCode()用来判断确定hash值是否相同

equals()用来判断属性的值是否相同

– equals()判断数据如果相等,hashCode()必须相同

– equals()判断数据如果不等,hashCode()尽量不同

package Again;

import java.util.HashMap;
import java.util.Iterator;

public class APIHashMap {
	public static void main(String[] args) {
		HashMap<Integer,String> map=new HashMap<>();
		map.put(1, "xixi");
		map.put(2, "value");
		System.out.println(map);
	}
}
TreeMap

6.多线程

6.1进程:

独立性:进程是系统中独立存在的实体,它可以拥有自己的独立的资源,每一个进程都拥有自己私有的地址空间。在没有经过进程本身允许的情况下,一个用户进程不可以直接访问其他进程的地址空间。

动态性:进程与程序的区别在于,程序只是一个静态的指令集合,而进程是一个正在系统中活动的指令集合。在进程中加入了时间的概念,进程具有自己的生命周期和各种不同的状态,这些概念在程序中都是不具备的。

并发性:多个进程可以在单个处理器上并发执行,多个进程之间不会互相影响。

6.2线程

线程(thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一个进程可以开启多个线程。

多线程扩展了多进程的概念,使得同一个进程可以同时并发处理多个任务。

如果一个进程只有一个线程,这种程序被称为单线程。

如果一个进程中有多条执行路径被称为多线程程序。

6.3进程和线程的区别

​ – 1一个软件的运行最少需要一个进程支撑,一个进程又可以启动多个线程来执行。
​ – 线程是进程的实际单位。也是操作系统可调度的最小单位。
​ – 如果一个进程,只包含一个线程 — 单线程程序
​ – 如果一个进程,包含多个线程 — 多线程程序
​ --2、并发和并行的区别
​ – 如果只有一个CPU在干活,大家都去抢占了CPU资源,发生了资源被抢占的现象–并发
​ – 假设有多个CPU在干活,每个CPU干一个任务,只不过是多个CPU一起各干各的–并行
​ --3、多线状态
​ --5种:新建状态–可运行状态–运行状态–阻塞状态–终止状态

​ 1) 新建状态(New):当线程对象对创建后,即进入了新建状态,如:Thread t = new MyThread();

​ 2) 就绪状态(Runnable):当调用线程对象的start()方法(t.start();),线程即进入就绪状态。处于就绪状态的线程,只是说明此线程已经做好了准备,随时等待CPU调度执行,并不是说执行了t.start()此线程立即就会执行;

​ 3) 运行状态(Running):当CPU开始调度处于就绪状态的线程时,此时线程才得以真正执行,即进入到运行状态。注:就绪状态是进入到运行状态的唯一入口,也就是说,线程要想进入运行状态执行,首先必须处于就绪状态中;

​ 4) 阻塞状态(Blocked):处于运行状态中的线程由于某种原因,暂时放弃对CPU的使用权,停止执行,此时进入阻塞状态,直到其进入到就绪状态,才有机会再次被CPU调用以进入到运行状态; 根据阻塞产生的原因不同,阻塞状态又可以分为三种:

​ a) 等待阻塞:运行状态中的线程执行wait()方法,使本线程进入到等待阻塞状态;

​ b) 同步阻塞:线程在获取synchronized同步锁失败(因为锁被其它线程所占用),它会进入同步阻塞状态;

​ c) 其他阻塞:通过调用线程的sleep()或join()或发出了I/O请求时,线程会进入到阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。

​ 5) 死亡状态(Dead):线程执行完了或者因异常退出了run()方法,该线程结束生命周期。

6.4Thread
public class APINet01 {
	public static void main(String[] args) {
		MyThread thread1=new MyThread();
		MyThread thread2=new MyThread();
		thread1.start();
		thread2.start();
		//start() 和run() 区别:start()可以实现多线程效果。run()只是当做一个普通的方法调用是一个顺序执行的效果。
		thread1.setName("Tom");
		thread2.setName("Bob");
	}
}
class MyThread extends Thread{

	@Override
	public void run() {
		// TODO Auto-generated method stub
	//	super.run();
		for(int i=0;i<10;i++) {
			System.out.println(i+"="+getName());
		}
	}
}
6.5Runnable
package APIthread;

public class APIJavaRunnable {
	public static void main(String[] args) {
		MyRunnable target=new MyRunnable();
		Thread thread1=new Thread(target);
		Thread thread2=new Thread(target);
		thread1.start();
		thread2.start();
		thread1.setName("Tom");
		thread2.setName("Bob");
	}
}
class MyRunnable implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<10;i++) {
			System.out.println(i+"=="+Thread.currentThread().getName());
		}
	}
}
6.6互斥锁

synchronized可以修饰方法称为同步方法。也可以修饰代码块称为同步代码块。使用关键字synchronized实现同步。是牺牲了效率提高了安全。

package xixi;

public class xxxx {
	public static void main(String[] args) {
		//创建线程对象
		MyTicket target=new MyTicket();
		//启动线程
		Thread t1=new Thread(target);
		t1.start();
		Thread t2=new Thread(target);
		t2.start();
		Thread t3=new Thread(target);
		t3.start();
		Thread t4=new Thread(target);
		t4.start();
	}
}
class MyTicket implements Runnable{
	int tickets=100;
	String s="abc";
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			//同步锁的位置:是从问题发生点开始,到结束为止
			//同步锁的对象:如果是同步代码块,根本不关心锁对象是谁,只要是同一个对象就可以。
			//synchronized(new object()){}每个代码都有自己的对象
			//synchronized(obj){多个代码使用了同一个对象obj,可以解决问题}
			//同步可以修饰方法,如果方法里的代码都有安全隐患,直接修饰成同步方法就可以了。
			synchronized(s) {
				if(tickets>0) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+"="+tickets--);
				}
				else {
					break;
				}
			}
		}
	}
	
}

7.单例设计模式

只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例。

package xixi;

public class hhh {
	public static void main(String[] args) {
		//调用MySingleton内部创建好的对象
				MySingleton m1=MySingleton.getSingle();
				MySingleton m2=MySingleton.getSingle();
				System.out.println(m1==m2);
	}
}
class MySingleton{
	//私有化构造方法,不能再外界随意创建对象
	private MySingleton() {}
	//在类的内部提供创建好的对象
	private static MySingleton single=new MySingleton();//饿汉式,直接new
	//提供返回MySingleton类型的对象
	public static MySingleton getSingle() {
		return single;
	}
}

class MySingleton2{
	//私有化构造方法,不能再外界随意创建对象
	private MySingleton2() {}
	//在类的内部提供创建好的对象
	private static MySingleton2 single;//懒汉式,不会立即new,什么时候需要什么时候new
	//提供返回MySingleton类型的对象
	public static MySingleton2 getSingle() {
		synchronized(MySingleton.class) {//共享资源是静态的,此时,说对象必须是MySingleton2的字节码对象
		if(single==null) {
			single=new MySingleton2();
		}
		return single;
		}
	}
}

8.注解

注解有一个标志:@,如@Override.

JDK自带注解:只有五个。@Override,@Deprecated(对于已经过期的方法,不提示已经过期),@SuppressWarnings(“deprecation”)(忽略警告),@SafeVarargs (jdk1.7出现,堆污染,不常用),@FunctionallInterface (jdk 1.8出现,配合函数式编程拉姆达表达式)

元注解:五个。@Target 注解用在哪里:类上,方法上,属性上。@Rentention 注解的生命周期:源文件中,class文件中,运行中。@Inherited 允许子注解继承。@Documented 生成javadoc时会包含注解,不常用。@Repeatable注解为可重复类型注解,可以在同一个地方多次使用,不常用。

描述注解的使用范围:

ElementType.ANNOTATION_TYPE 应用于注释类型

ElementType.CONSTRUCTOR 应用于构造函数

ElementType.FIELD 应用于字段或属性

ElementType.LOCAL_VARIABLE 应用于局部变量

ElementType.METHOD 应用于方法级

ElementType.PACKAGE 应用于包声明

ElementType.PARAMETER 应用于方法的参数

ElementType.TYPE 应用于类的元素

SOURCE 在源文件中有效(即源文件保留)

CLASS 在class文件中有效(即class保留)

RUNTIME 在运行时有效(即运行时保留)

package xixi;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class zhujie {
	public static void main(String[] args) {
	}
}
//创建注解
@Target({ElementType.TYPE,ElementType.METHOD})//指定注解位置--可以出现在类上。
@Retention(RetentionPolicy.SOURCE)//指定注解的生命周期--在源码中有效
@interface Test{
	//String name();//给注解添加属性--后面后括号
	//String name() default "";//给了属性默认值,调用的时候可给属性值也可以不给属性值。
	String value();//value时特殊属性,可以简写
} 
//@Test
//@Test(name="hello")//给name()属性赋值
@Test("heh")
class Hello{
	String name;
	public void method(){
		System.out.println(123);
	}
}

9.反射

Class.forName("");

类名.class//获取本类的对象

对象.getclass();

//--1、创建学生类
		package cn.tedu.reflection;
		//这个类用来测试 反射
		public class Student {
			public Student() {}
			public Student(String name) {
				this.name=name;
			}
			public Student(int age) {
				this.age = age;
			}
			public Student(String name, int age) {
				this.name = name;
				this.age = age;
			}
			//最好设置成public的,不然反射不到了
			public String name ;
			public int age ;		
			public void save() {
				System.out.println("save()...");
			}
			public void show(int num) {
				System.out.println("show()..."+num);
			}		
			//重写toString();为了方便看对象的属性值而不是地址值
			@Override
			public String toString() {
				return "Student [name=" + name + ", age=" + age + "]";
			}			
		}
	//--2、反射类中的资源
		package cn.tedu.reflection;

		import java.lang.reflect.Constructor;
		import java.lang.reflect.Field;
		import java.lang.reflect.Method;
		import java.util.Arrays;

		import org.junit.Test;
		//这个类用来测试  反射获取学生类里的所有数据
		//Junit单元测试方法: @Test   + void  + 没有参数
		//运行:必须选中方法名,右键,run  as  , junit test...
		public class Test3_Reflection2 {
			//利用反射创建对象
			@Test
			public void showObject() throws Exception {
				//1、获取Class对象
				Class<?> clazz = Student.class;
				//2、利用反射,创建对象
				Object obj = clazz.newInstance();//触发了无参构造
				//cn.tedu.reflection.Student@443b7951
				System.out.println(obj);
				//怎么触发含参构造
				//指定你想要触发 哪个 含参构造   
		//		clazz.getConstructor(String.class);//触发string类型的含参构造
		//		clazz.getConstructor(int.class);//触发int类型的含参构造
				Constructor c = clazz.getConstructor(String.class , int.class);
				Object obj2 = c.newInstance("皮皮霞",20);//给构造方法传参
				//cn.tedu.reflection.Student@14514713
				//Student [name=皮皮霞, age=20]
				System.out.println(obj2);
			}
			
			//获取学生类中的成员变量们
			@Test
			public void showFields() {
				//1、获取Class对象
				Class<?> clazz = Student.class;
				
				//2、获取所有   公共的   的属性们  
				Field[] fs = clazz.getFields() ; 
				
				//3、遍历数组
				for (Field f : fs) {
					//4、获取变量名
					String name = f.getName() ;
					System.out.println(name);
					
					//5、获取变量的类型
					String type = f.getType().getName();
					System.out.println(type);
				}
			}
			
			//获取学生类中的构造方法们
			@Test
			public void showConstructor() {
				// 1、获取Class对象
				Class<?> clazz = Student.class;
				// 2、调用方法
				Constructor<?>[] cs = clazz.getConstructors() ;
				//3、遍历数组
				for(Constructor c : cs) {
					//4、获取方法名
					String name = c.getName();
					System.out.println(name);
					
					//5、获取参数的类型
					Class[] cls = c.getParameterTypes() ;
					System.out.println( Arrays.toString(cls)  );
				}
			}
			
			// 获取学生类中的成员方法们
			@Test
			public void showMethod() {
				// 1、获取Class对象
				Class<?> clazz = Student.class;
				// 2、调用方法
				Method[] ms = clazz.getMethods();
				// 3、遍历数组
				for (Method m : ms) {
					// 4、获取方法名
					String name = m.getName();
					System.out.println(name);
					//5、获取方法有没有参数
					Class<?>[] cls = m.getParameterTypes();
					System.out.println(  Arrays.toString(cls)  );
				}
			}
			
			@Test
			public void showClass() throws ClassNotFoundException {
				// 反射Class对象
				Class<?> clazz = Class.forName("cn.tedu.reflection.Student");
				Class<?> clazz2 = Student.class;
				Student s = new Student();
				Class<?> clazz3 = s.getClass();
				System.out.println(clazz);
				System.out.println(clazz2);
				System.out.println(clazz3);
			}
		}

暴力反射

//--1、创建Person类
		package cn.tedu.reflection;
		//这个类用来 测试暴力反射
		public class Person {		
			private String name = "张三";
			private int age = 20 ;
			
			private void show() {
				System.out.println("show()...");
			}
			public void test(int a) {
				System.out.println("test()..."+a);
			}			
		}	
	//--2、暴力反射
		package cn.tedu.reflection;

		import java.lang.reflect.Method;
		import java.util.Arrays;

		import org.junit.Test;

		//这个类用来 测试暴力反射Person 
		public class Test4_ReflectPrivate {
			//暴力反射成员方法
			@Test
			public void showMethod() throws Exception {
				//1、获取Class对象
				Class clazz = Class.forName("cn.tedu.reflection.Person");
				
				//2、获取所有的方法们
		//		clazz.getMethods();  //反射  公共的  资源
				
		//3、暴力反射  --  所有   方法们  ---  getDeclaredMethods()--可以获取公共的或者私有的方法
				Method[] ms = clazz.getDeclaredMethods(); 
				for (Method m : ms) {
					String name = m.getName();
					System.out.println(name);
					Class<?>[] cls = m.getParameterTypes();
					System.out.println(  Arrays.toString(cls) );	
				}
				//4、暴力反射    --   获取    单个   方法
				//getDeclaredMethod(m,n)-m是想要执行的方法名 -n是方法需要的参数类型
				Method method = clazz.getDeclaredMethod("show", null);
				//5、如何执行
				//--invoke(m,n)-m是想让哪个对象执行方法-n是方法需要的参数
				//!!设置私有可见
				method.setAccessible(true);
				Object obj = clazz.newInstance() ;
				method.invoke(obj, null) ;
			}
			//TODO 暴力反射成员变量	
		}

10.内部类

package xixi;

public class OTest {
	public static void main(String[] args) {

		//内部类,可以看作外部类A的特殊成员
		//位置不同,内部类的名字和作用不同
		//-- 如果是在成员位置(类里方法外)- 成员内部类  --  用!!
		//-- 如果是在局部位置(方法里)-局部内部类  ----   不用!!
		//-- 匿名内部类   -- 最常用!!
		//-- 内部类可以直接访问外部类中的成员,包括私有成员
		//-- 外部类要访问内部类的成员,必须要建立内部类的对象
		//当内部类被static修饰后,可以直接被类名调用
        //neibulei.Inner in2=new neibulei.Inner();
        
		//创建内部类对象:外部类.内部类 变量名=外部类对象,内部类对象
		neibulei.Inner in=new neibulei().new Inner();
		in.get();
		System.out.println(in.name);
		
	}
}
package xixi;

public class neibulei {
	int age=18;
	public void save() {
		System.out.println("InnerClass.save()");
		Inner a=new Inner();
		a.get();
	}
	//外部类访问内部类需要创建内部类对象
	
	//成员内部类
	class Inner{
		String name="xxx";
		public void get(){
			//内部类可以直接访问外部类成员,包括私有的
			System.out.println(age);
			//save();重复交替访问,死循环
			System.out.println("haha");
		}
	}
}

匿名内部类

package xixi;

public class nimingneibulei {
	public static void main(String[] args) {
		//接口不能创建对象
		//但是如果同时使用了匿名对象和匿名内部类是可以直接new的,就相当于创建了接口的实现类
		//匿名对象用起来方便。但是一次只执行一个任务。
		new Inter1() {

			@Override
			public void save() {
				// TODO Auto-generated method stub
				System.out.println("save()");
			}
			@Override
			public void get() {
				// TODO Auto-generated method stub
				System.out.println("get()");
			}
			
		}.save();
		//配合匿名内部类抽象类可以被new
		new AdstractDemo() {

			@Override
			public void sleep() {
				// TODO Auto-generated method stub
				System.out.println("wwwwwwwwww");
				}
			}.sleep();
	}
}
//定义接口
interface Inter1{
	void save();
	void get();
}

abstract class AdstractDemo{
	public void eat() {
		System.out.println("eat()...");
	}
	abstract public void sleep();
}

11.套接字

服务器

package socketcode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class servera {
	public static void main(String[] args) {
		try {
			//创建服务器对象,表示在该端口上,等待客户端的连接请求
			//参数是端口号:默认是1~65535,其中0-1024被系统占用
			ServerSocket server=new ServerSocket(8000);
			//开始接受客户端的请求,并建立了数据传输通道Socket
			Socket socket=server.accept();
			System.out.println("链接成功");
			//接受读取客户端发来的数据
			InputStream in=socket.getInputStream();
			for(int i=0;i<5;i++) {
				char b=(char)in.read();
				System.out.print(b);
			}
			

			//服务器给客户端发送数据
			OutputStream out1=socket.getOutputStream();
			//开始写出数据
			out1.write("world".getBytes());
			out1.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

客户端

package socketcode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class clientb {
	public static void main(String[] args) {
		//链接指定的服务器
		try {
			//连接本机ip和服务器端口
			Socket socket=new Socket("127.0.0.1",8000);
			//给服务器发送数据
			OutputStream out=socket.getOutputStream();
			out.write("Hello".getBytes());
			out.flush();
			//客户端读取服务器发回来的数据
			InputStream in=socket.getInputStream();
			//开始正是读取数据
			for(int i=0;i<5;i++) {
				char c=(char)in.read();
				System.out.print(c);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值