一、异常
Error:错误无法解决的问题。
Exception:外部问题出现的异常
常见的异常:空指针等等
二、异常的处理(抓抛异常)
处理方法一:try。。。catch。。。finally
finally是可选的
try{
//可能出现的错误
}catch(异常类型1 变量1){
}catch(异常类型2 变量2){
}....
finally{
//一定会执行的代码
}
从小往大写(否则报错),catch抓住了只会执行一次
public class HelloWorld {
public static void main(String[] args) {
String str ="abc";
try {
int num = Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("出现异常了哦");
e.printStackTrace();
}
System.out.println("hello");
}
}
finally的使用:是可选的,及时catch中出现了错误,finally当中也要释放资源
处理方式二:throws + 异常类型
public class HelloWorld {
public static void main(String[] args) {
try {
fun();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void fun() throws Exception{
String str = "abc";
int num = Integer.parseInt(str);
System.out.println("hello");
}
}
try...catch...finally真正将异常处理掉了
throws方式只是将异常抛给调用者
两个的选择:如果父类被重写的没有throws异常,则方法也不能用throws,如果子类有就用try cathc捕获
手动抛异常 : throws new RuntimeException("传入是局部匹配")
三、多线程
1.多线程创建的方式一
- 继承Thread类的子类
- 重写Thread类的run() ==>将要执行的操作写在run方法中
- 创建Thread类的子类的对象
- 通过此对象调用start()
public class HelloWorld {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println("*"+i);
}
}
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
注意我们不能直接调用run()方法,只能调用start()
开启两次线程需要再实例化一次对象
练习两个线程做其他的事情
public class HelloWorld {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println("Thread1 "+i);
}
}
}
}
class MyThread2 extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
System.out.println("Thread2 "+i);
}
}
}
}
常用方法:
start():启动当前线程:调用当前的线程的run()
run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
currentThread():静态方法,返回当前代码的线程
getName():获取当前线程的名字
setName():设置当前线程的名字
yield():释放cpu的执行权
join():在线程a中调用b的join(),此时线程a就进入阻塞状态,知道线程b执行完,a在执行
sleep():让当前线程
public class HelloWorld {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
t1.setName("线程一");
t1.start();
//给主线程命名
Thread.currentThread().setName("主线程");
}
}
class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println("Thread1 "+i+Thread.currentThread().getName());
}
}
}
}
class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println("Thread1 "+i+Thread.currentThread().getName());
}
if (i % 2 == 0) {
this.yield();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
线程的优先级
- MAX_PRIORITY:10
- MIN_PRIORITY:1
- NORM_PRIORITY:5 --->默认优先级
t1.sePriority(Thread.MAX_PRIORITY) 设置优先级
t1.getPriority():获取优先级
高优先级抢占cpu的执行权高,但不是讲百分之百执行
实现卖票案例,存在安全问题
public class HelloWorld {
public static void main(String[] args) {
Window w1 = new Window();
Window w2 = new Window();
Window w3 = new Window();
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
class Window extends Thread{
private int ticket =100;
@Override
public void run() {
while (true){
if(ticket >0){
System.out.println(getName()+" 票号为:" +ticket);
ticket--;
}else{
break;
}
}
}
}
三、创建多线程的方式二:实现Runnable接口
- 创建一个实现了Runnable接口
- 实现类去实现Runnable中的抽象方法:run()
- 创建实现类的对象
- 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
- 通过Thread类的对象调用start()
public class HelloWorld {
public static void main(String[] args) {
Window window = new Window();
Thread w1 = new Thread(window);
Thread w2 = new Thread(window);
Thread w3 = new Thread(window);
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口");
w1.start();
w2.start();
w3.start();
}
}
class Window implements Runnable{
private int tickets = 100;
public void run() {
while (true){
if(tickets > 0 ){
System.out.println(Thread.currentThread().getName()+"票号为:"+tickets);
tickets--;
}else{
break;
}
}
}
}
两个创建方式的区别:
开发中常用:继承Runnable类的创建方式
原因1:实现没有单继承的局限性,实现的方式更适合来处理多个线程共享数据的问题(不用static)
线程的生命周期
新建、就绪、运行、阻塞、死亡
线程的同步(买票重复的解决)
在java中通过同步机制,来解决线程安全问题
1.解决实现接口Runnable的线程安全问题
方式一:同步代码块
//方式一
syschronized(同步监视器){
//需要被同步的方法
}
//操作共享数据的代码,即被称为需要被同步的代码
//共享数据:多个线程操作的变量
//同步监视器成为,锁,任何一个类都可以称为对象,所有线程需要共用一把锁
//补充,可以考虑this,充当锁,但是要保证他是唯一的
public class HelloWorld {
public static void main(String[] args) {
Window window = new Window();
Thread w1 = new Thread(window);
Thread w2 = new Thread(window);
Thread w3 = new Thread(window);
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
class Window implements Runnable{
private int tickets = 1000;
Object object = new Object(); //一样的,唯一就可以
Dog dog = new Dog(); //一样的,唯一就可以
public void run() {
while (true){
synchronized (object){
if(tickets > 0 ){
System.out.println(Thread.currentThread().getName()+"票号为:"+tickets);
tickets--;
}else{
break;
}
}
}
}
}
class Dog{
}
方式二、同步方法
public class HelloWorld {
public static void main(String[] args) {
Window window = new Window();
Thread w1 = new Thread(window);
Thread w2 = new Thread(window);
Thread w3 = new Thread(window);
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
class Window implements Runnable {
private int tickets = 1000;
public void run() {
while (true) {
show();
}
}
public synchronized void show() {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "票号为:" + tickets);
tickets--;
}
}
}
方式三、lock锁
- 先实例化一个ReentrantLock
- 前调用lock 后 使用 unlock解锁,手动启动lock,手动释放unlock
import java.util.concurrent.locks.ReentrantLock;
public class HelloWorld {
public static void main(String[] args) {
Window window = new Window();
Thread w1 = new Thread(window);
Thread w2 = new Thread(window);
Thread w3 = new Thread(window);
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
class Window implements Runnable {
private ReentrantLock reentrantLock = new ReentrantLock();
private int tickets = 100;
public void run() {
while (true) {
reentrantLock.lock();
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "票号为:" + tickets);
tickets--;
}
reentrantLock.unlock();
}
}
}
顺序lock-->同步代码块-->同步方法
线程的通信
wait():一旦执行此方法,当前线程进入阻塞,并释放同步监视器
notify():一旦执行此方法,就会唤醒wait的一个线程,优先级高的await就会被唤醒
notifyAll():一旦执行此方法,所有await的线程都会被唤醒
这些方法都必须使用在同步代码块或同步方法中。三个方法的调用者必须是同步代码块和同步监视器
这三个方法定义在Object里面
经典例题:生产者/消费者问题
public class HelloWorld {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk);
p1.setName("生产者1");
Customer c1 = new Customer(clerk);
c1.setName("消费者1");
Customer c2 = new Customer(clerk);
c2.setName("消费者2");
p1.start();
c1.start();
c2.start();
}
}
class Clerk{
private int productCount = 0;
// 生产产品
public synchronized void produceProduct() {
if(productCount < 20){
productCount++;
System.out.println(Thread.currentThread().getName()+":开始生产第"+productCount+"个产品");
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void consumeProduct() {
if(productCount > 0){
System.out.println(Thread.currentThread().getName()+":开始消费第"+productCount+"个产品");
productCount--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{
private Clerk clerk;
public Producer(Clerk clerk){
this.clerk= clerk;
}
@Override
public void run() {
System.out.println(getName()+":开始生产产品。。。。");
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceProduct();
}
}
}
class Customer extends Thread{
private Clerk clerk;
public Customer(Clerk clerk){
this.clerk= clerk;
}
@Override
public void run() {
System.out.println(getName()+":开始消费产品。。。。");
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.consumeProduct();
}
}
}
三、创建多线程的方式 实现callable接口
- 创建一个实现Callable的实现类
- 实现call方法,将线程需要执行的操作声明在call()中
- 主线程创建Callable接口实现类的对象
- 将此Callable接口实现的对象作为传递到FutrueTask构造器中,创建Futuretask对象
- 将FutrueTask的对象作为参数传递到Thread构造类的构造器中,创建Thread对象,并调用start()
- 获取callable中call的返回值
- get()返回值即为FutrueTask构造器参数的实现类重写的call()的返回值。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class HelloWorld {
public static void main(String[] args) {
NumThread numThread = new NumThread();
FutureTask futureTask = new FutureTask(numThread);
new Thread(futureTask).start();
try {
Object o = futureTask.get();
System.out.println("返回值是"+o);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class NumThread implements Callable{
private int i = 0;
public Object call() throws Exception {
for (int j = 0; j < 100; j++) {
System.out.println(i);
i++;
}
return 123;
}
}
四、创建线程的方法:线程池
好处:1.提高响应速度,2、降低资源消耗、3,便于线程管理
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class NumberThread implements Runnable{
public void run() {
for(int i = 0 ; i < 100; i ++ ){
if(i%2 == 0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
class NumberThread1 implements Runnable{
public void run() {
for(int i = 0 ; i < 100; i ++ ){
if(i%2 == 0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
public class HelloWorld {
public static void main(String[] args) {
// 创建固定的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new NumberThread()); //适合使用Runnable
service.execute(new NumberThread1()); //适合使用Runnable
//service.submit(); //适合使用Callable
// 关闭连接池
service.shutdown();
}
}
五、Java常用类
String相关的类
string字符串的使用:" ",支持序列化,可以比较大小。字符串常量池当中不会存储相同的字符串
赋值:String str = "abc" String str = new String("abc")
int length():返回字符串的长度
char charAt(int index):返回某索引的字符
boolean isEmpty():判断字符串是否为空
String toLowerCase():将所有字符变成小写
String toUpCase():将所有字符变成大写
String trim():返回字串,去除前后空格的字符串
boolean equals(Object obj) 比较字符串内容是否相同
boolean equalsIgnoreCase(String str):比较忽略大小写的字串比较
String concat(Sring str) 连接字符串,相当于加号
int compareTo(String str) 比较两个字符串的大小
String subString(int beginindex):返回一个新的字符串从beginIndex开始截取
String subString(int beginindex,int endIndex):返回一个新的字符串从beginIndex开始截取到endIndex
boolean endsWith(String suffix):测试字符串是否以指定后缀结束
boolean startWith(String prefix):测试字符串是否以指定前缀开始
boolean startWith(String prefix,int toffset):测试字符串是否以指定前缀开始,且在指定的索引
boolean containes(char s) :测试字符串是否包含某个字符
int indexOf(Stirng str): 返回字符串第一次出现的索引
int indexOf(Stirng str,int fromIndex): 返回字符串第一次出现的索引,在指定位置
int lastIndexOf(String str):字符串最后一次出现的位置
int lastindexOf(Stirng str,int fromIndex): 返回字符串最后一次出现的索引,在指定位置
String replace(char oldchar , char newchar) 返回一个新的字符串
String replaceAll(String regx,String replacement) 通过正则替换
String replaceFirst(String regx,String replacement) 通过正则替换第一个
boolean matches(String regx) 匹配正则表达式
String[] split(String regx)根据正则才分字符串
String[] split(String regx,int limit)根据正则才分字符串,加上限制
String -- >int integer.parseInt("123") int -->String String.valueOf(123)
StringBuffer与StringBuilder相关类
append(String str),字符串拼接
delete(int start,int end):删除指定字符串
replace(int start,int end,String str):替换字符串
insert(int offset,xxx):在指定位置插入xxx
reverse():把当前字符串进行反转
indexOf(Stirng sr)
subString(int start,int end)
chartAt(int n)
setCharAt(int i , char ch)
日期函数
Date
- System.currentTimeMillis(); 返回时间戳
- Date date = new Date() date.toString():显示当前的年月日 date.getTime()获取时间戳
- 获取指定时间 new Date(传入时间戳) 返回的时间
SimpleDateFormat类
- SimpleDateFormat的实例化 SimpleDateFormat s = new SimpleDateFormat() s.format(new Date())
- 逆过程:s = "19-12-18 上午11:43" s.parse(str)
- 格式化 SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
Calendar(日历)类
查文档
LocalDate、LocalTime、localDateTime
查文档
Instant
查文档
DateTimeFormatter(格式化时间)
查文档
比较器
Arrays.sort(arr) 可以进行排序
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
String[] arr = new String[]{"AA","CC","LL","DD","EE"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
} //[AA, CC, DD, EE, LL]
Arrays.sort()排列自定义的类
实现接口comparable 重写 comparator的方法 自然排序
import java.lang.reflect.Array;
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
Goods[] arr = new Goods[5];
arr[0] = new Goods("lenoveMouse",35);
arr[1] = new Goods("dellMouse",98);
arr[2] = new Goods("xiaomiMouse",89);
arr[3] = new Goods("huaweiMouse",67);
arr[4] = new Goods("microsoftMouse",43);
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].toString());
}
}
}
class Goods implements Comparable{
private String name;
private double price;
public Goods(){
}
public Goods(String name,double price){
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
public int compareTo(Object o) {
if( o instanceof Goods){
Goods goods = (Goods) o;
//方式一:
if(this.price >goods.price ){
return 1;
}else if(this.price < goods.price){
return -1;
}else{
return 0;
}
//方式二:
// return Double.compare(this.price,goods.price);
}
// return 0;
throw new RuntimeException("传入的数据不一致");
}
}
comparator接口的使用:定制排序
import java.util.Arrays;
import java.util.Comparator;
public class HelloWorld {
public static void main(String[] args) {
String[] arr = new String[]{"AA","DD","EE","CC","BB"};
Arrays.sort(arr,new Comparator(){
public int compare(Object o1, Object o2) {
if(o1 instanceof String&&o2 instanceof String){
String s1 = (String) o1;
String s2 = (String) o2;
return -s1.compareTo(s2);
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr)); //[EE, DD, CC, BB, AA]
}
}
自定义的类
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
public class HelloWorld {
public static void main(String[] args) {
Goods[] arr = new Goods[5];
arr[0] = new Goods("lenoveMouse", 35);
arr[1] = new Goods("dellMouse", 98);
arr[2] = new Goods("xiaomiMouse", 89);
arr[3] = new Goods("huaweiMouse", 67);
arr[4] = new Goods("microsoftMouse", 43);
Arrays.sort(arr, new Comparator() {
//指明商品比较大小的方式:按照产品名称从高到低排序,在按价格从高到底
public int compare(Object o1, Object o2) {
if (o1 instanceof Goods && o2 instanceof Goods){
Goods g1 = (Goods) o1;
Goods g2 = (Goods) o2;
if(g1.getName().equals(g2.getName())){
return -Double.compare(g1.getPrice(), g2.getPrice());
}else{
return g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("数据输入有误");
}
});
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].toString());
}
}
}
class Goods implements Comparable {
private String name;
private double price;
public Goods() {
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
public int compareTo(Object o) {
if (o instanceof Goods) {
Goods goods = (Goods) o;
//方式一:
if (this.price > goods.price) {
return 1;
} else if (this.price < goods.price) {
return -1;
} else {
return 0;
}
//方式二:
// return Double.compare(this.price,goods.price);
}
// return 0;
throw new RuntimeException("传入的数据不一致");
}
}
System系统类 查文档
Math数学类
BigInteger与BigDecimal 查文档
枚举类
当需要定义许多常量就用枚举
jdk:5.0之前:自定义枚举类
public class HelloWorld {
public static void main(String[] args) {
Season spring = Season.Spring;
System.out.println(spring);
}
}
class Season{
// 1.声明Season对象的属性:private final 修饰
private final String seasonName;
private final String seasonDesc;
// 2.私有化构造器,并给属性赋值
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
// 3/提供当前类的多个对象:public static final的
public static final Season Spring = new Season("春天","春意盎然");
public static final Season SUMMER = new Season("夏天","夏日炎炎");
public static final Season AUTUMN = new Season("秋天","秋高气爽");
public static final Season WINTER = new Season("冬天","冰天雪地");
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
jdk:5.0之后:enum
public class HelloWorld {
public static void main(String[] args) {
Season spring = Season.Spring;
System.out.println(spring);
}
}
enum Season {
Spring("春天", "春意盎然"),
SUMMER("夏天", "夏日炎炎"),
AUTUMN("秋天", "秋高气爽"),
WINTER("冬天", "冰天雪地");
// 1.声明Season对象的属性:private final 修饰
private final String seasonName;
private final String seasonDesc;
// 2.私有化构造器,并给属性赋值
private Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
}
注解
@Override:限定重写父类方法
@Deprecated:用于修饰过时的元素
@SuppressWarnings:抑制编译器警告
集合
1.集合、数组都是对多个数据进行存储操作的结构,简称java容器
2.不涉及持久化存储
Collection接口
1)常用方法
Colleaction coll = new ArrayList()
添加一个:coll.add()
获得数组的大小:coll.size()
添加许多数据:coll.addAll()
判断是否非空:coll.isEmpty()
清空集合:coll.clear()
判断是否包含某个元素 coll.contains()
判断某个集合是否都在这个集合里:coll.containsAll()
移除某个元素:coll.remove(123)
移除多个元素:coll.removeAll(123,123)
求两个集合的交集:coll.retainAll(coll1)
判断两个集合是否相等:coll.equals(obj)
获取一个随机值:coll.hashCode()
集合转数组:coll.toArray()
数组转集合:Array.asList(arr)
Iterator遍历Collection:
public class HelloWorld {
public static void main(String[] args) {
Collection cl = new ArrayList();
cl.add("123");
cl.add("456");
cl.add("789");
cl.add("098");
cl.add("765");
Iterator iterator = cl.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
foreach循环遍历
public class HelloWorld {
public static void main(String[] args) {
Collection cl = new ArrayList();
cl.add("123");
cl.add("456");
cl.add("789");
cl.add("098");
cl.add("765");
for (Object obj : cl){
System.out.println(obj);
}
}
}
foreach遍历数组
int[] arr = new int[]{1,2,3,4,5,6};
for (int i : arr){
System.out.println(i);
}
Collection的子接口List
ArrayList LinkedList Vector
public class HelloWorld {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(123);
arrayList.add(456);
arrayList.add("abc");
arrayList.add(new Date());
System.out.println(arrayList);
// arrayList.add(int index,Collection eles);从index处开始添加元素
System.out.println(arrayList.get(1)); //获取某个索引的值
System.out.println(arrayList.indexOf(456)); //返回第一个出现这个的位置
System.out.println(arrayList.lastIndexOf(456));//返回最后出现这个的位置
// arrayList.remove(1) 删除索引
// arrayList.set(int index,value) 设置某个索引的值
// System.out.println(arrayList.subList(1,3)); 返回区间的值
}
}
Set结构
HashSet
public class HelloWorld {
public static void main(String[] args) {
Set set = new HashSet();
set.add(123);
set.add(456);
set.add("AA");
set.add(new Date());
}
}
HashLinked
public class HelloWorld {
public static void main(String[] args) {
Set set = new LinkedHashSet(); //效率比hashSet高
set.add(123);
set.add(456);
set.add("AA");
set.add(new Date());
}
}
TreeSet
public class HelloWorld {
public static void main(String[] args) {
Set set = new TreeSet(); //效率比hashSet高
set.add(123);
set.add(456);
set.add("AA");
set.add(new Date());
System.out.println(set.size());
}
}
Map接口
map中的key:无序的、不可重复的、使用Set存储所有的key。value是无序的,可重复的,使用Collection存储所有value
HashMap:效率高,频繁操作使用LinkedHashMap
TreeMap
HashTable(不用了) Properties(处理属性文件)
import java.util.HashMap;
import java.util.Map;
public class HelloWorld {
public static void main(String[] args) {
Map map1 = new HashMap();
map1.put("BB",789);
Map map = new HashMap();
map.put("AA",123); //添加一个元素
map.put("AA",456); //修改一个元素
map.putAll(map1); //添加一个map
map.remove("AA");//移除一个元素
// map.clear(); //清除
map.size();//返回大小
map.get("BB");//获取指定key的值
map.containsKey("BB");//是否包含这个key值
map.containsValue(123);//是否包含这个Value值
map.isEmpty();//判断是否为空
}
}
遍历
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Map map = new HashMap();
map.put("AA",123);
map.put("BB",789);
map.put("CC",456);
map.put("DD",901);
//遍历所有的key集:keySet()
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//遍历所有的Value值
Collection values = map.values();
for (Object o : values){
System.out.println(o);
}
//遍历所有的Key-Value值
Set entrySet = map.entrySet();
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()){
Object o = iterator1.next();
Map.Entry entry =(Map.Entry) o;
System.out.println(entry.getKey()+"===>"+entry.getValue());
}
}
}
TreeMap
Map map = new TreeMap();
map.put("AA",123);
map.put("BB",789);
map.put("CC",456);
map.put("DD",901); //可以实现排序
Properties pros = new Properties(); 配置文件属性
工具类
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
List list = new ArrayList();
list.add(123);
list.add(43);
list.add(-89);
list.add(0);
System.out.println(list);
// Collections.reverse(list); //反转
// Collections.shuffle(list); //排序
// Collections.sort(list); //排序
Collections.swap(list,1,2);
// 返回线程安全的List
List list1 = Collections.synchronizedList(list);
System.out.println(list1);
}
}
泛型
泛型用于检查,编译时保证数据的安全
public class HelloWorld {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(456);
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("A",123);
// 泛型的嵌套
Set<Map.Entry<String,Integer>> entry = map.entrySet();
}
}
自定义泛型类
多个<K,V,T>多个用逗号隔开
public class HelloWorld {
public static void main(String[] args) {
// 如果定义了泛型类,但是没有使用则是Object,如果使用了泛型,那么就要用上
Order order = new Order();
// 建议实例化时指明泛型
Order<String> order1 = new Order<String>("orderAA",1001,"order:AA");
// order1.setOrderT(); String
SubOrder subOrder = new SubOrder();
// subOrder.setOrderT(); //integer
}
}
//自定义泛型类
class Order<T> {
String orderName;
int orderId;
// 类的内部结构就可以使用类的泛型
T orderT;
public Order() {
}
public Order(String orderName, int orderId, T orderT) {
this.orderName = orderName;
this.orderId = orderId;
this.orderT = orderT;
}
public T getOrderT() {
return orderT;
}
public void setOrderT(T orderT) {
this.orderT = orderT;
}
}
class SubOrder extends Order<Integer>{
}
自定义泛型方法:查文档
泛型通配符::通配符:?
public class HelloWorld {
public static void main(String[] args) {
List<Object> list1 = null;
List<String> list2 = null;
List<?> list = null;
}
}
IO流
File类
package com.baidu.exer;
import java.io.File;
import java.io.IOException;
public class FileHello {
public static void main(String[] args) throws IOException {
// 常用方法
// File file1 = new File("hello.txt");
File file1 = new File("D:\\javaSE最新代码\\File\\File\\src\\hello.txt"); //绝对路径
System.out.println(file1.getAbsoluteFile()); //获取绝对路径
System.out.println(file1.getPath()); //获取路径
System.out.println(file1.getName()); //获取名称
System.out.println(file1.getParent());//获取上层目录路径
System.out.println(file1.length()); //获取文件长度
System.out.println(file1.lastModified());//获取最后一次修改时间
System.out.println(file1.list());//获取数组名称
System.out.println(file1.listFiles());//获取所哟名称
System.out.println(file1.isFile());//判断是否是文件
System.out.println(file1.isDirectory());//判断是否是文件
System.out.println(file1.exists());//判断是否存在
System.out.println(file1.canRead());//判断是否可读
System.out.println(file1.canWrite());//判断是否可写
System.out.println(file1.isHidden());//判断是否隐藏
//创建功能方法
File file3 = new File("h1.txt");
if(!file3.exists()){
file3.createNewFile();//创建文件
System.out.println("创建成功");
}else{
file3.delete();//删除文件
System.out.println("删除成功");
}
//文件目录的创建
File file4 = new File("D:\\javaSE最新代码\\File\\File\\src\\hah");
boolean mkdir = file4.mkdir();//创建目录
if (mkdir){
System.out.println("创建目录成功");
}
//文件目录的多级创建
File file5 = new File("D:\\javaSE最新代码\\File\\File\\src\\heh\\he");
boolean mkdirs = file4.mkdirs();//创建目录
if (mkdirs){
System.out.println("创建多级目录成功");
}
}
}
IO流的使用
主方法文件位置相当于src
普通方法文件位置相当于model
结论:1.对于文本文件(.txt,.java,.c,.cpp)使用字符流处理
2.对于非文本文件(.avi.map3)使用字节流处理
读取数据的操作 FileReader
package com.baidu.exer;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileHello {
public static void main(String[] args) {
/*流的分类
1.操作数据单位:字节流、字符流
2.数据的流向:输入流、输出流
3.流的角色:节点流、处理流
二、流的体系
抽象基类 节点流 缓冲流
InputStream FileInputStream BufferedFileInputStream
OutputStream FileOutputStream BufferedFileOutputStream
Reader FileReader BufferedFileReader
Writer FileWriter BufferedFileWriter
*/
/*
* 1.read()的理解:返回读取的一个字符,如果达到文件末尾返回-1
* 2.异常处理用try—catch-finally处理
* 3.要读入的文件一定要存在否则会报错
* */
//读取硬盘文件,并输出到控制台
FileReader fr = null;
try {
// 1.实例化File类的对象,指明要操作的文件
File file = new File("h1.txt");
// 2.提供具体的流
fr = new FileReader(file);
// 3.数据的读入
int data = fr.read();
while (data != -1) {
System.out.print((char) data);
data = fr.read(); //相当于i++,没有了就返回-1
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.流的关闭
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
对FileRead(上面)的升级read()的优化
ctrl+alt+z:实现方法哦
public class FileHello {
public static void main(String[] args) {
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("h1.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cubf):返回每次读入cbuf数组中字符的个数。如果达到文件某位,返回-1
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
//方式一
//for (int i = 0; i < len; i++) {
// System.out.print(cbuf[i]);
//}
//方式二
String str = new String()
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.资源的关闭
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
从内存中写出数据到硬盘
package com.baidu.exer;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileHello {
public static void main(String[] args) {
//输出操作,对应的文件可以不存在
//如果不存在,会自动创建这个文件
//如果存在,会被覆盖
FileWriter fw = null;
try {
//1.File类的实例化
File file = new File("h1.txt");
//2.FileReader流的实例化
//第一参数为文件,第二个参数为是否追加,true追加,false覆盖
fw = new FileWriter(file,true);
//3.写入的操作
fw.write("I have a dream");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.资源的关闭
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字符流不能处理图片(FileRead与FileWrite不可以)
FileInputStream(读) FileOutStream(写)
public class FileHello {
public static void main(String[] args) {
FileInputStream fis = null;
try {
//1.File类的实例化
File file = new File("h1.txt");
//2.FileReader流的实例化
//第一参数为文件,第二个参数为是否追加,true追加,false覆盖
fis = new FileInputStream(file);
//3.写入的操作
int len;
byte[] buffer = new byte[5];
while ((len = fis.read(buffer)) != -1){
String str = new String(buffer,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.资源的关闭
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
实现图片的复制
public class FileHello {
public static void main(String[] args) {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
File srcFile = new File("hah.png");
File destFile = new File("hah(1).png");
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
缓冲流的使用
bos.flush()刷新缓冲区 BufferInputStream BufferOutStream非文本
package com.baidu.exer;
import java.io.*;
import java.util.Scanner;
public class FileHello {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件 实现非文本文件复制
File srcFile = new File("h1.txt");
File destFile = new File("h2.txt");
//2.造流
//2.1造节点流
fis = new FileInputStream((srcFile));
fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//复制的细节读出与写入
byte[] buffer = new byte[5];
int len;
while ((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭:要求先关外面,再关里面
// bos.close();
// bis.close();
//说明:关闭外流层的时候,内流层就会关闭,所以我们一般就关闭外面就可以
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferRead与BufferWrier实现文本复制
package com.baidu.exer;
import java.io.*;
import java.util.Scanner;
public class FileHello {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
//创建文件对应的流
br = new BufferedReader(new FileReader(new File("h1.txt")));
bw = new BufferedWriter(new FileWriter(new File("h3.txt")));
//读写操作
char[] cbuf = new char[5];
int len;
while ((len = br.read(cbuf)) != -1){
bw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
转换流
InputStreamReader:字节输入流到字符的输入流
public class FileHello {
// 任然应该使用try-catch-finally,偷个懒直接抛出去了
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("h1.txt");
// InputStreamReader isr = new InputStreamReader(fis);//默认的字符集,jdk
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] cbuf = new char[5];
int len;
while ((len = isr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
}
}
结合使用
package com.baidu.exer;
import java.io.*;
import java.util.Scanner;
public class FileHello {
// 任然应该使用try-catch-finally,偷个懒直接抛出去了
public static void main(String[] args) throws IOException {
File file1 = new File("h1.txt");
File file2 = new File("h4.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
char[] cbuf = new char[3];
int len;
while ((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
isr.close();
osw.close();
}
}
对象流、将内存中的java对象保存到磁盘中通过网络传输出去使用objectpuStream实现
public class FileHello {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 序列化:存入,内存放入到磁盘
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱天安门"));
oos.flush();//操作刷新
oos.close();
//反序列化:读取,磁盘文件还原为内存
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String) obj;
System.out.println(str);
}
}
网络编程
IP InetAddress
public class FileHello {
public static void main(String[] args) {
// ip地址,域名(www.baidu.com)、端口
// 协议
try {
//实例化InetAddress
InetAddress inet1 = InetAddress.getByName("192.168.137.1");
System.out.println(inet1);
InetAddress inet2 = InetAddress.getByName("www.aitguigu.com");
System.out.println(inet2);
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
System.out.println(inet3);
//获取本地ip
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet4);
//获取HostName
System.out.println(inet4.getHostName());
//获取InetAddress
System.out.println(inet4.getAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
实现TCP编程
案例1:客户端发送内容给服务端,服务端将内容打印到控制台上。
客户端代码:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class code1 {
public static void main(String[] args) {
//客户端
Socket socket = null;
OutputStream os =null;
try {
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
socket = new Socket(inetAddress,8899);
os = socket.getOutputStream();
os.write("hello world,I have a dream".getBytes());
System.out.println("发送成功");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务段代码:
package com.baidu.exer;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class FileHello {
public static void main(String[] args) {
//实现TCP编程
ServerSocket ss = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
try {
//1.创建服务端的ServerSocket,指明自己的端口号
ss = new ServerSocket(8899);
//2.调用accept()表示接收来自于客户端的socket
socket = ss.accept();
//3.获取输入流
inputStream = socket.getInputStream();
//4.读取输入流中的数据
// 不建议这样写有乱码
// int len;
// byte[] buffer = new byte[20];
// while ((len=inputStream.read(buffer)) != -1){
// String s = new String(buffer, 0, len);
// System.out.print(s);
// }
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭资源
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
案例二:客户端发送文件给服务端,服务端将数据保存在本地
客户端:
package com.baidu.exer;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class FileHello {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 8090);
os = socket.getOutputStream();
fis = new FileInputStream(new File("hah.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
package com.baidu.exer2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
//服务端
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
ss = new ServerSocket(8090);
socket = ss.accept();
is = socket.getInputStream();
fos = new FileOutputStream(new File("hah2.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
案例三:客户端给服务端发送数据成功后,服务端给客户端发送成功给客户端
客户端:
package com.baidu.exer;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class FileHello {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 8090);
os = socket.getOutputStream();
fis = new FileInputStream(new File("hah.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
//接收来自服务端的数据,并显示到控制台
InputStream is = socket.getInputStream();
byte[] buffer1 = new byte[1024];
int len1;
while ((len1 = is.read(buffer1)) != -1) {
System.out.println(buffer);
System.out.println(new String(buffer1,len,1));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
public static void main(String[] args) {
//服务端
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
ss = new ServerSocket(8090);
socket = ss.accept();
is = socket.getInputStream();
fos = new FileOutputStream(new File("hah3.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
//服务端给与客户端
OutputStream os = socket.getOutputStream();
os.write("你好,美女,照片我收到了很漂亮".getBytes());//发出信息
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}