0
点赞
收藏
分享

微信扫一扫

【Java架构】JavaSE核心知识点总结三

七:IO流

一、

   1. 流的概念:流是有起点和终点的一组有顺序的字节集合,作用是进行数据传输

   2. 流的分类

       1. 按照数据流向不同可以分为输入输出流;

       2. 按照处理数据单位不同可以分为字节流和字符流

   3. 输入流和输出流的作用



       1. 输入流:程序从数据源读取数据

       2. 输出流:将数据从程序中写入指定文件

   4. 字节流和字符流的作用



       1. 字节流:以字节为单位处理所有类型数据    

       2. 字符流:以字符为单位处理纯文本文件



二、体系结构

    IO流

在这里插入图片描述

三、常用方法

    IO流常用方法

在这里插入图片描述

四、常用方法实现文本文件复制

1 import java.io.FileInputStream;
2 import java.io.FileNotFoundException;
3 import java.io.FileOutputStream;
4 import java.io.FileReader;
5 import java.io.FileWriter;
6 import java.io.IOException;
7
8 /**
9 * 1. 文本文件复制
10 * @author DELL
11 *
12 */
13 public class TestIO {
14 public static void main(String[] args) {
15 // 要读取的文件
16 String src = “E:/Workspaces1/Demo/src/TestFile.java”;
17 // File src = new File(“路径”);
18 // 要写入的文件
19 String dest = “d:/test.java”;
20
21 // 1.1 一次复制一个字节
22 copyFile1(src, dest);
23 // 1.2 一次复制一个字节数组
24 copyFile2(src, dest);
25
26 // 2.1 一次复制一个字符
27 copyFile3(src, dest);
28 // 2.2 一次复制一个字符数组
29 copyFile4(src, dest);
30 }
31
32 // 1. 一次复制一个字节,异常处理,手动关闭流
33 public static void copyFile1(String srcFileName, String destFileName) {
34 FileInputStream fis = null;
35 FileOutputStream fos = null;
36 try {
37 fis = new FileInputStream(srcFileName);
38 fos = new FileOutputStream(destFileName);
39 int cc = fis.read();
40 while (cc != -1) {
41 // 一次写入一个字节
42 fos.write(cc);
43 // 一次写入一个字节
44 cc = fis.read();
45 }
46 } catch (FileNotFoundException e) {
47 e.printStackTrace();
48 } catch (IOException e) {
49 e.printStackTrace();
50 } finally {
51 if (fos != null) {
52 try {
53 fos.close();
54 } catch (IOException e) {
55 e.printStackTrace();
56 }
57 }
58 if (fis != null) {
59 try {
60 fis.close();
61 } catch (IOException e) {
62 e.printStackTrace();
63 }
64 }
65 }
66 }
67
68 // 2. 一次复制一个字节数组,异常处理,自动关闭流
69 public static void copyFile2(String srcFileName, String destFileName) {
70 // 自动关闭流
71 try (
72 FileInputStream fis = new FileInputStream(srcFileName);
73 FileOutputStream fos = new FileOutputStream(destFileName);
74 ) {
75 byte[] bytes = new byte[1024];
76 int len = fis.read(bytes);
77 while (len != -1) {
78 // 一次写入一个字节数组
79 fos.write(bytes, 0, len);
80 // 一次读取一个字节数组
81 len = fis.read(bytes);
82 }
83 } catch (FileNotFoundException e) {
84 e.printStackTrace();
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89
90 // 3. 一次复制一个字符,异常处理,自动关闭流
91 public static void copyFile3(String srcFileName, String destFileName) {
92 try (
93 FileReader fr = new FileReader(srcFileName);
94 FileWriter fw = new FileWriter(destFileName);
95 ){
96 int cc = fr.read();
97 while (cc != -1) {
98 // 一次写入一个字符
99 fw.write(cc);
100 // 一次读取一个字符
101 cc = fr.read();
102 }
103 } catch (FileNotFoundException e) {
104 e.printStackTrace();
105 } catch (Exception e) {
106 e.printStackTrace();
107 }
108 }
109
110 // 4. 一次复制一个字符数组,异常处理,手动关闭流
111 public static void copyFile4(String srcFileName, String destFileName) {
112 FileReader fr = null;
113 FileWriter fw = null;
114 try {
115 fr = new FileReader(srcFileName);
116 fw = new FileWriter(destFileName);
117 char[] cbuf = new char[1024];
118 int len = fr.read(cbuf);
119 while (len != -1) {
120 // 一次写入一个字符数组
121 fw.write(cbuf);
122 // 一次读取一个字符数组
123 len = fr.read(cbuf);
124 }
125 } catch (FileNotFoundException e) {
126 e.printStackTrace();
127 } catch (IOException e) {
128 e.printStackTrace();
129 } finally {
130 if (fw != null) {
131 try {
132 fw.close();
133 } catch (IOException e) {
134 e.printStackTrace();
135 }
136 }
137 if (fr != null) {
138 try {
139 fr.close();
140 } catch (IOException e) {
141 e.printStackTrace();
142 }
143 }
144 }
145 }
146 }

五、序列化和反序列化

   1. 序列化和反序列化的概念

       1. 对象序列化:把对象转换为字节序列(二进制数据)的过程

       2. 对象反序列化:把字节序列恢复为对象的过程



   2. 什么情况下需要序列化

       1. 将对象保存到文件或数据库中时

       2. 使用套接字在网上传送对象时

       3. 通过RMI传输对象时



   3. 如何实现序列化

       1. 创建类实现Serializable接口

       2. 指定serialVersionUID序列号

       3. 使用对象输出流(ObjectOutputStream)将对象保存到指定位置

       4. 使用writerObject()方法将对象写入到文件中



   4. 哪些属性不能被序列化

       1. 使用transient修饰的属性

       2. 使用static修饰的属性



   5. 序列化和反序列化代码实现

1 // 1. 创建类实现Serializable接口
2 class People implements Serializable {
3
4 // 2. 指定序列号
5 private static final long serialVersionUID = 1L;
6 // 静态字段
7 private static String id = “2019”;
8 // transient关键字修饰的字段
9 private transient String name;
10
11 private Integer age;
12
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20
21 public Integer getAge() {
22 return age;
23 }
24
25 public void setAge(Integer age) {
26 this.age = age;
27 }
28
29 @Override
30 public String toString() {
31 return “People [name=” + name + “, age=” + age + “]”;
32 }
33
34 }
35
36 public class Test {
37 public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
38 serializePeople();
39 deserializePeople();
40 }
41
42 /**
43 * 序列化
44 /
45 public static void serializePeople() throws FileNotFoundException, IOException {
46 People p = new People();
47 p.setName(“张三”);
48 p.setAge(18);
49 // 3. 使用对象输出流将对象保存到指定位置
50 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(“D:/test.txt”)));
51 // 4. 将对象写入文件
52 oos.writeObject§;
53 System.out.println(“对象序列化成功!!”);
54 oos.close();
55 }
56
57 /
*
58 * 反序列化
59 */
60 public static People deserializePeople() throws ClassNotFoundException, IOException {
61 // 使用对象输入流从指定位置读取对象
62 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(“D:/test.txt”)));
63 // 读取对象
64 People p = (People) ois.readObject();
65 System.out.println(“对象反序列化成功!!”);
66 return p;
67
68 }
69 }

六、File 类常用方法

1 import java.io.File;
2 import java.io.FileFilter;
3 import java.io.IOException;
4 import java.text.SimpleDateFormat;
5
6 public class TestFile {
7 public static void main(String[] args) throws IOException {
8 // 1. 构造方法指明文件路径以及格式
9 File file = new File(“D:\test2\test.txt”);
10 File file2 = new File(“D:\test2”);
11 File file3 = new File(“D:\test3”);
12
13 // 2.1 创建一个文件
14 file.createNewFile();
15 // 2.2 创建一个单级目录
16 file2.mkdir();
17 // 2.3 创建一个多级目录
18 file3.mkdirs();
19
20 // 3.1 判断文件或文件夹是否存在
21 System.out.println(file.exists()); // true
22 // 3.2 判断是否为绝对路径
23 System.out.println(file.isAbsolute()); // true
24 // 3.3 判断是否为文件
25 System.out.println(file2.isFile()); // false
26 // 3.4 判断是否为目录
27 System.out.println(file2.isDirectory()); // true
28 // 3.5 判断是否为隐藏文件
29 System.out.println(file3.isHidden()); // false
30
31 // 4.1 获取文件或目录名称
32 System.out.println(file.getName());
33 // 4.2 获取文件的绝对路径
34 System.out.println(file.getAbsolutePath());
35 // 4.3 获取文件相对路径
36 System.out.println(file.getPath());
37 // 4.4 获取文件父目录
38 System.out.println(file.getParent());
39 // 4.5 获取文件大小
40 System.out.println(file.length());
41 // 4.6 获取文件最后一次被修改时间
42 SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
43 String updateTime = sdf.format(file.lastModified());
44 System.out.println(updateTime);
45
46 // 5.1 返回此目录下的所有文件和目录
47 String [] fileString = file2.list();
48 for (String str : fileString) {
49 System.out.println(str);
50 }
51 // 5.2 返回此目录下的所有文件
52 File [] files = file2.listFiles();
53 for (File file4 : files) {
54 System.out.println(file4.getName());
55 }
56 // 5.3 返回所有根目录
57 File [] files2 = File.listRoots();
58 for (File file4 : files2) {
59 System.out.println(file4);
60 }
61 // 5.4 返回指定目录中符合过滤条件的文件和目录
62 File [] files3 = file2.listFiles(new FileFilter() {
63
64 @Override
65 public boolean accept(File pathname) {
66 while (“a.txt”.equals(pathname.getName())){
67 return true;
68 }
69 return false;
70 }
71 });
72 for (File file4 : files3) {
73 System.out.println(file4.getName());
74 }
75 }
76 }

八:多线程

一、简介

   1. 线程和进程

       1. 进程:操作系统中的应用程序,一个进程就是一个应用程序

       2. 线程:CPU调度的最小单元,进程的一个执行流。对于新手小白想更轻松的学好Java提升,Java架构,web开发、大数据,数据分析,人工智能等技术,这里给大家分享系统教学资源,扩列下我尉(同英):CGMX9880 【教程/工具/方法/解疑】



   2. 上下文切换

       1. 上下文切换:CPU从一个线程或进程切换到另一个进程或线程;

       2. 多线程程序并不是同时进行的,由于CPU的执行速度太快,CPU会在不同的线程之间快速的切换执行;



二、实现方式

1 import java.util.concurrent.Callable;
2 import java.util.concurrent.FutureTask;
3
4 /**
5 * 1. 创建多线程的三种方式
6 * 1. 继承Thread类
7 *
8 * 2. 实现Runnable接口
9 * 1. 方式一:创建类实现Runnable接口
10 * 1. 创建类实现Runnable接口
11 * 2. 重写run()方法
12 * 3. 使用Thread类的构造方法实例化实现Runnable接口的类对象
13 * 4. 开启线程
14 *
15 * 2. 方式二:使用匿名内部类
16 * 1. 使用Thread类的构造方法创建一个Runnable接口的代理对象
17 * 2. 重写run()方法
18 * 2. 开启线程
19 *
20 * 3. 实现Callable接口
21 * 1. 方式一:创建类实现Callable接口
22 * 1. 创建类实现Callable接口
23 * 2. 重写call()方法
24 * 3. 使用Thread类的构造方法实例化FutureTask对象
25 * 4. 使用FutureTask类的构造方法实例化实现了Callable接口的类对象
26 * 5. 开启线程
27 *
28 * 2. 方式二:使用匿名内部类
29 * 1. 使用Thread类的构造方法实例化FutureTask对象
30 * 2. 使用FutureTask类的构造方法创建Callable接口的代理对象
31 * 3. 重写call()方法
32 * 4. 开启线程
33 *
34 * 2. 三种方式的优缺点
35 * 1. 继承了Thread类
36 * 1. 优点:代码书写简单
37 * 2. 缺点:由于Java的单继承性,代码的耦合度比较高
38 *
39 * 2. 实现了Runnable接口和Callable接口
40 * 1. 方式一:
41 * 1. 优点:代码的可扩展性更强
42 * 2. 缺点:没有缺点
43 *
44 * 2. 方式二:
45 * 1. 优点:代码书写简单
46 * 2. 缺点:只适合线程使用一次的时候
47 /
48
49
50 /
*
51 * 1. 继承Thread类
52 /
53 class Thread1 extends Thread{
54 public static void test() {
55 for (int i = 0; i < 100; i++) {
56 System.out.println(“继承Thread类执行的第” + i + “次”);
57 }
58 }
59 }
60
61 /
*
62 * 2. 实现Runnable接口
63 /
64 class Thread2 implements Runnable{
65
66 @Override
67 public void run() {
68 for (int i = 0; i < 100; i++) {
69 System.out.println(“实现Runnable接口方式一执行的第” + i + “次”);
70 }
71 }
72 }
73
74 /
*
75 * 3. 实现Callable接口
76 */
77 class Thread3 implements Callable{
78 @Override
79 public Integer call() throws Exception {
80 int i = 0;
81 for (; i < 100; i++) {
82 System.out.println(“实现Callable接口方式一执行的第” + i + “次”);
83 }
84 return i;
85 }
86 }
87
88 public class TestThread {
89 public static void main(String[] args) {
90 // 1. 测试继承Thread类
91 Thread1 thread1 = new Thread1();
92 thread1.start();
93 Thread1.test();
94
95
96 // 2. 测试实现Runnable接口
97 // 2.1 方式一
98 new Thread(new Thread2()).start();
99
100 // 2.2 方式二
101 new Thread(new Runnable() {
102 @Override
103 public void run() {
104 for (int i = 0; i < 100; i++) {
105 System.out.println(“实现Runnable接口方式一执行的第” + i + “次”);
106 }
107 }
108 }).start();
109
110
111 // 3. 测试实现Callable接口
112 // 3.1 方式一
113 new Thread(new FutureTask(new Thread3() {
114 }), “方式三”).start();;
115
116 // 3.2 方式二
117 new Thread(new FutureTask(new Callable() {
118 @Override
119 public Integer call() throws Exception {
120 int i = 0;
121 for (; i < 100; i++) {
122 System.out.println(“实现Runnable接口方式二执行的第” + i + “次”);
123 }
124 return i;
125 }
126 })).start();;
127 }
128 }

三、常用方法

   1. 方法图

在这里插入图片描述

   2. 常用方法代码实现

1 public class TestThreadMethod {
2 public static void main(String[] args) {
3 Thread thread = new Thread(new Runnable() {
4 @Override
5 public void run() {
6 for (int i = 0; i < 100; i++) {
7 // 获取正在执行的线程对象的引用
8 System.out.println(Thread.currentThread().getName() + “执行的第” + i + “次”);
9 }
10 }
11 });
12 // 1. 开启线程
13 thread.start();
14
15
16 // 2. 设置
17 // 2.1 设置该线程名称
18 thread.setName(“线程1号”);
19 // 2.2 设置该线程为守护线程:main方法结束之后该线程停止
20 //thread.setDaemon(true);
21 // 2.3 设置该线程的优先级
22 thread.setPriority(7);
23
24
25 // 3. 获取
26 // 3.1 获取线程名称
27 System.out.println(thread.getName()); // 线程1号
28 // 3.2 获取线程标识符
29 System.out.println(thread.getId()); // 13
30 // 3.3 获取线程优先级
31 System.out.println(thread.getPriority()); // 7
32 // 3.4 获取线程状态
33 System.out.println(thread.getState()); // RUNNABLE
34 // 3.5 获取线程所在线程组
35 System.out.println(thread.getThreadGroup()); // java.lang.ThreadGroup[name=main,maxpri=10]
36
37
38 // 4. 判断
39 // 4.1 判断线程是否中断
40 System.out.println(thread.isInterrupted()); // false
41 // 4.2 判断线程是否为活动状态
42 System.out.println(thread.isAlive()); // true
43 // 4.3 判断线程是否为守护线程
44 System.out.println(thread.isDaemon()); // false
45
46
47 // 5. 停
48 // 5.1 让线程休眠指定毫秒数
49 new Thread(new Runnable() {
50 @Override
51 public void run() {
52 for (int i = 0; i < 50; i++) {
53 System.out.println(Thread.currentThread().getName() + “执行的第” + i + “次”);
54 if (i == 25) {
55 try {
56 /**
57 * 1. sleep()是静态方法
58 * 2. sleep()使用时必须捕获异常
59 * 3. sleep()执行时,只是让该线程进入阻塞状态,并不会释放锁
60 /
61 System.out.println(“线程2号正在休眠”);
62 Thread.sleep(5000);
63 } catch (InterruptedException e) {
64 e.printStackTrace();
65 }
66 }
67 }
68 }
69 },“线程2号”).start();
70
71 // 5.2 暂停当前线程去执行其他线程
72 new Thread(new Runnable() {
73 @Override
74 public void run() {
75 for (int i = 0; i < 50; i++) {
76 System.out.println(Thread.currentThread().getName() + “执行了” + i + “次”);
77 if (i == 25) {
78 /
*
79 * 1. yield()是静态方法
80 * 2. yield()执行时,让线程进入就绪状态,重新争抢CPU执行权,并不会释放锁
81 /
82 Thread.yield();
83 }
84 }
85 }
86 },“线程3号”).start();
87
88 // 5.3 等待线程销毁
89 new Thread(new Runnable() {
90 @Override
91 public void run() {
92 for (int i = 0; i < 100; i++) {
93 if (i == 50) {
94 /
*
95 * 1. join()是对象方法
96 * 2. join()使用时必须捕获异常
97 * 3. join()使用场景:一个执行完的线程需要另一个正在执行的线程的运行结果时
98 */
99 System.out.println(“线程1号正在销毁!!!!”);
100 try {
101 thread.join();
102 } catch (InterruptedException e) {
103 e.printStackTrace();
104 }
105 System.out.println(“线程1号销毁成功!!!!”);
106 }
107 }
108 }
109 },“线程4号”).start();
110
111 }
112 }

四、线程同步

1 import java.util.concurrent.locks.Lock;
2 import java.util.concurrent.locks.ReentrantLock;
3
4
5 /**
6 * 1. 线程安全
7 * 1. 什么是线程安全:当多个线程同时操作同一共享数据时,导致共享数据出错
8 * 2. 怎样解决:使用线程同步技术
9 *
10 * 2. 线程同步:将多个线程的数据共享
11 *
12 * 3. 实现线程同步的方式
13 * 1. 同步代码块:有synchronized关键字修饰的语句块
14 * 1. 实例代码块:锁对象是this或者任意对象
15 * 2. 静态代码块:锁对象是当前类的字节码文件
16 *
17 * 2. 同步方法: 有synchronized关键字修饰的方法
18 * 1. 实例方法
19 * 2. 静态方法
20 *
21 * 3. 使用重入锁
22 * 1. 声明锁对象
23 * 2. 给共享数据上锁
24 * 3. 在finally中解锁
25 *
26 * 4. wait()和notify()
27 * wait(): 线程等待,释放锁
28 * notify(): 唤醒等待状态线程
29 /
30
31 class Bank{
32 // 实例账户
33 private Integer account1 = 100;
34 // 静态账户
35 private static Integer account2 = 100;
36 // 1. 声明锁对象
37 private Lock lock = new ReentrantLock();
38
39
40
41 /
*
42 * 1. 同步代码块
43 /
44 // 存钱1
45 public void save1(Integer money) {
46 // 实例代码块
47 synchronized (this) {
48 account1 += money;
49 }
50 System.out.println(Thread.currentThread().getName() + “存入了” + money + “元”);
51 }
52 // 取钱1
53 public void draw1(Integer money) {
54 // 实例代码块
55 synchronized (this) {
56 if (account1 - money < 0) {
57 System.out.println(“账户余额不足”);
58 return;
59 }
60 account1 -= money;
61 System.out.println(Thread.currentThread().getName() + “取出了” + money + “元”);
62 }
63 }
64 // 存钱2
65 public static void save2(Integer money) {
66 // 静态代码块
67 synchronized (Bank.class) {
68 account2 += money;
69 }
70 System.out.println(Thread.currentThread().getName() + “存入了” + money + “元”);
71 }
72 // 取钱2
73 public static void draw2(Integer money) {
74 // 静态代码块
75 synchronized (Bank.class) {
76 if (account2 - money < 0) {
77 System.out.println(“余额不足”);
78 return;
79 }
80 account2 -= money;
81 System.out.println(Thread.currentThread().getName() + “取出了” + money + “元”);
82 }
83 }
84
85 /
*
86 * 2. 同步方法
87 /
88 // 2.1 实例方法
89 public synchronized void save3(Integer money) {
90 account1 += money;
91 System.out.println(Thread.currentThread().getName() + “存入了” + money + “元”);
92 }
93 public synchronized void draw3(Integer money) {
94 if (account1 - money < 0) {
95 System.out.println(“余额不足”);
96 return;
97 }
98 account1 -= money;
99 System.out.println(Thread.currentThread().getName() + “取出了” + money + “元”);
100 }
101
102 // 2.2 静态方法
103 public synchronized static void save4(Integer money) {
104 account2 += money;
105 System.out.println(Thread.currentThread().getName() + “存入了” + money + “元”);
106 }
107 public synchronized static void draw4(Integer money) {
108 if (account2 - money < 0) {
109 System.out.println(“余额不足”);
110 return;
111 }
112 account2 -= money;
113 System.out.println(Thread.currentThread().getName() + “取出了” + money + “元”);
114 }
115
116
117 /
*
118 * 3. 重入锁
119 /
120 public void save5(Integer money) {
121 // 2. 上锁
122 lock.lock();
123 try {
124 account1 += money;
125 System.out.println(Thread.currentThread().getName() + “存入了” + money + “元”);
126 } finally {
127 // 3. 解锁
128 lock.unlock();
129 }
130 }
131 public void draw5(Integer money) {
132 // 2. 上锁
133 lock.lock();
134 try {
135 if (account1 - money < 0) {
136 System.out.println(“余额不足”);
137 return;
138 }
139 account1 -= money;
140 System.out.println(Thread.currentThread().getName() + “取出了” + money + “元”);
141 } finally {
142 // 3. 解锁
143 lock.unlock();
144 }
145 }
146
147 // 查看账户余额
148 public void show() {
149 System.out.println(“实例账户余额” + account1);
150 System.out.println(“静态账户余额” + account2);
151 }
152
153 }
154
155 class Demo implements Runnable{
156 private static Bank bank = new Bank();
157 @Override
158 public void run() {
159 /
*
160 * 1. 测试同步代码块
161 /
162 // 1.1 实例代码块
163 bank.save1(100);
164 bank.show();
165 bank.draw1(20);
166 bank.show();
167
168 // 1.2 静态代码块
169 Bank.save2(100);
170 bank.show();
171 Bank.draw2(20);
172 bank.show();
173
174 /
*
175 * 2. 测试同步方法
176 /
177 // 2.1 实例方法
178 bank.save3(100);
179 bank.show();
180 bank.draw3(20);
181 bank.show();
182 // 2.2 静态方法
183 Bank.save4(100);
184 bank.show();
185 Bank.draw4(20);
186 bank.show();
187
188 /
*
189 * 3. 测试重入锁
190 */
191 bank.save5(100);
192 bank.show();
193 bank.draw5(20);
194 bank.show();
195 }
196 }
197
198 public class TestSynchronized {
199 public static void main(String[] args) {
200 // 1. 测试同步实例代码块
201 new Thread(new Demo(),“线程1号”).start();
202 // 2. 测试同步静态代码块
203 new Thread(new Demo(),“线程2号”).start();
204
205 // 2. 测试同步方法
206 // 2.1 实例方法
207 new Thread(new Demo(),“线程3号”).start();
208 // 2.2 静态方法
209 new Thread(new Demo(),“线程4号”).start();
210
211 // 3. 测试冲入锁
212 new Thread(new Demo(),“线程5号”).start();
213
214 }
215 }

五、线程控制(线程状态转换图)

    线程状态转换图

在这里插入图片描述

九:网络编程

一、简介

   1. 概述

       1. 计算机网络:多台算机之间实现信息传递和资源共享的的计算机系统

       2. 网络编程:不同计算机之间使用网络进行数据交换



   2. 三要素

       1. IP:每个设备在网络中的唯一标识

       2. 端口号:每个程序在设备上的唯一标识

       3. 协议:在网络中进行数据交换要遵守的规则



   3. UDP与TCP的区别

       1. UDP:面向无连接,数据不可靠,速度快,适用于高速传输和对实时性要求较高

       2. TCP:面向连接,数据可靠,速度略低,适用于可靠传输



二、操作

   1. 常用方法 

       网络编程常用方法

在这里插入图片描述

   2. UDP传输代码实现

1 import java.io.IOException;
2 import java.net.DatagramPacket;
3 import java.net.DatagramSocket;
4 import java.net.SocketException;
5
6 /**
7 * 1. 服务器端实现步骤
8 * 1. 创建服务器对象
9 * 2. 将接受到的数据打包
10 * 3. 将数据包存储到服务器对象
11 * 4. 打印数据
12 * 5. 关闭流通道
13 *
14 * 2. 客户端步骤实现
15 * 1. 创建客户端对象
16 * 2. 将数据打包
17 * 3. 发送数据包
18 * 4. 关闭流通道
19 *
20 * @author 萌萌哥的春天
21 *
22 /
23
24
25 /
*
26 * 服务器端
27 /
28 public class Server {
29 public static void main(String[] args) throws IOException {
30 // 1. 创建服务器对象
31 DatagramSocket ds = new DatagramSocket(9102);
32
33 // 2. 将接收到的数据打包
34 byte[] bytes = new byte[1024];
35 DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
36
37 // 3. 将数据包存入服务器对象
38 ds.receive(dp);
39
40 // 4. 打印数据
41 String IP = dp.getAddress().getHostAddress(); // IP地址
42 int port = dp.getPort();
43 String data = new String(dp.getData(), 0, dp.getLength()); // 将字节数组转为字符串
44 System.out.println(IP+": --" + data + “–” + port + “:”);
45
46 // 5. 关闭流通道
47 ds.close();
48 }
49 }
50
51 /
*
52 * 客户端
53 */
54 public class Client {
55 public static void main(String[] args) throws IOException {
56 // 1. 创建客户端对象
57 DatagramSocket ds = new DatagramSocket();
58
59 // 2. 将数据打包
60 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 接受键盘输入
61 byte[] bytes = br.toString().getBytes(); // 将字符串转换为字节数组
62 DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(“localhost”),9102);
63
64 // 3. 发送数据包
65 ds.send(dp);
66
67 // 4. 关闭流通道
68 ds.close();
69 }
70 }
71
72 复制代码

   3. TCP传输代码实现

1 import java.io.BufferedWriter;
2 import java.io.BufferedReader;
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.io.InputStreamReader;
9 import java.io.OutputStreamWriter;
10 import java.net.ServerSocket;
11 import java.net.Socket;
12 import java.net.UnknownHostException;
13
14 /**
15 * 1. 服务器端实现步骤
16 * 1. 创建服务器对象
17 * 2. 侦听客户端连接
18 * 3. 使用输入流读取客户端输入
19 * 4. 使用输出流写入文件
20 * 5. 使用输出流通知客户端
21 * 6. 关闭流通道
22 *
23 * 2. 客户端步骤实现
24 * 1. 创建客户端对象
25 * 2. 使用输出流发送数据到服务器
26 * 3. 使用输入流读取本地文件
27 * 4. 使用输入流接收服务器反馈并打印到控制台
28 * 5. 关闭流通道
29 *
30 * @author 萌萌哥的春天
31 *
32 /
33
34
35 /
*
36 * 服务器端
37 /
38 public class Server {
39 private static ServerSocket server;
40 private static Socket socket;
41 private static InputStream in;
42 private static OutputStream out;
43
44 public static void main(String[] args) {
45 try {
46 // 1. 创建服务器对象
47 server = new ServerSocket(9102);
48
49 // 2. 侦听客户端连接
50 socket = server.accept();
51
52 // 3. 使用输入流接收客户端输入
53 in = socket.getInputStream();
54
55 // 4. 使用输出流写入文件
56 out = new FileOutputStream(“D:/server.txt”);
57 byte[] bytes = new byte[1024];
58 int len = 0;
59 while ((len = in.read(bytes)) != -1) {
60 out.write(bytes, 0, len);
61 out.flush();
62 }
63
64 // 5. 使用输出流通知客户端
65 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
66 bw.write(“文件上传成功”);
67 bw.flush();
68
69 } catch (FileNotFoundException e) {
70 e.printStackTrace();
71 } catch (IOException e) {
72 e.printStackTrace();
73 } finally {
74 // 6. 关闭流通道
75 if (server != null) {
76 try {
77 server.close();
78 } catch (IOException e) {
79 e.printStackTrace();
80 }
81 }
82 if (socket != null) {
83 try {
84 socket.close();
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89 if (in != null) {
90 try {
91 in.close();
92 } catch (IOException e) {
93 e.printStackTrace();
94 }
95 }
96 if (out != null) {
97 try {
98 out.close();
99 } catch (IOException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }
105 }
106
107 /
*
108 * 客户端
109 */
110 public class Client {
111 private static Socket socket;
112 private static InputStream in;
113
114 public static void main(String[] args) {
115 try {
116 // 1. 创建客户端对象
117 socket = new Socket(“localhost”, 9102);
118
119 // 2. 使用输入流发送数据到服务器
120 OutputStream out = socket.getOutputStream();
121
122 // 3. 使用输入流读取本地文件
123 in = new FileInputStream(“D:/client.txt”);
124 byte[] bytes = new byte[1024];
125 int len = 0;
126 while ((len = in.read(bytes)) != -1) {
127 out.write(bytes, 0, len);
128 }
129
130 // 4. 通知服务器文件已上传
131 socket.shutdownOutput();
132
133 // 5. 使用输出流接收服务器反馈
134 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
135 System.out.println(br.readLine());
136
137 } catch (UnknownHostException e) {
138 e.printStackTrace();
139 } catch (FileNotFoundException e) {
140 e.printStackTrace();
141 } catch (IOException e) {
142 e.printStackTrace();
143 } finally {
144 // 6. 关闭流通道
145 if (socket != null) {
146 try {
147 socket.close();
148 } catch (IOException e) {
149 e.printStackTrace();
150 }
151 }
152 if (in != null) {
153 try {
154 in.close();
155 } catch (IOException e) {
156 e.printStackTrace();
157 }
158 }
159 }
160 }
161 }

十:反射

一、概述

   1. 反射机制:动态获取类的信息和调用对象的方法的功能

   2. 反射实现:获取每个类的字节码文件,也就是Class类对象



二、反射的方式

1 /**
2 * 反射的三种方式:推荐2和3
3 * 1. Object类的getClass()方法
4 * 2. 实体类.class
5 * 3. Class类的forName()方法
6 */
7
8
9 public class TestReflect {
10 public static void main(String[] args) {
11 // 1. 方式一:getClass()方法
12 Worker worker = new Worker();
13 Class<? extends Worker> class1 = worker.getClass();
14 System.out.println(class1.getName()); // Worker
15
16 // 2. 方式二:实体类.class
17 Class class2 = Worker.class;
18 System.out.println(class1 == class2); // true
19
20 // 3. 方式三:Class类的forName()方法
21 try {
22 Class<?> class3 = Class.forName(“Worker”);
23 System.out.println(class2 == class3); // true
24 } catch (ClassNotFoundException e) {
25 e.printStackTrace();
26 }
27 }
28 }

三、操作

   1. 常用方法

在这里插入图片描述

       Class类常用方法



   2. 常用方法代码实现

1 import java.lang.reflect.Constructor;
2 import java.lang.reflect.Field;
3 import java.lang.reflect.Method;
4
5 class Worker {
6 // 私有属性
7 private Integer id;
8 private String name;
9 // 公共属性
10 Integer age;
11
12 public Worker() {
13 }
14
15 public Worker(String name) {
16 this.name = name;
17 }
18
19 protected Worker(Integer id, String name) {
20 this.id = id;
21 this.name = name;
22 }
23
24 private Worker(Integer id, String name, Integer age) {
25 this.id = id;
26 this.name = name;
27 this.age = age;
28 }
29
30 // 继承方法
31 @Override
32 public String toString() {
33 return “Worker [id=” + id + “, name=” + name + “, age=” + age + “]”;
34 }
35
36 // 私有方法
37 private void test() {
38 System.out.println(“这是私有方法”);
39 }
40
41 }
42
43 public class TestReflect {
44 public static void main(String[] args) {
45 // 1. 创建Class对象
46 Class class1 = Worker.class;
47 Class class2 = String.class;
48
49
50 /**
51 * 2. 类相关操作
52 /
53
54 // 2.1 获取完整性类名
55 System.out.println(class2.getName()); // java.lang.String
56
57 // 2.2 获取类名
58 System.out.println(class2.getSimpleName()); // String
59
60 // 2.3 获取此类的包名
61 System.out.println(class2.getPackage()); // package java.lang
62
63 // 2.4 获取当前类所继承父类的名字
64 System.out.println(class2.getSuperclass()); // class java.lang.Object
65
66 // 2.5获取当前类实现的接口
67 Class<?>[] interfaces = class2.getInterfaces();
68 for (Class<?> class3 : interfaces) {
69 System.out.println(class3);
70 // interface java.io.Serializable
71 // interface java.lang.Comparable
72 // interface java.lang.CharSequence
73 }
74
75
76 /
*
77 * 3. 类中属性相关操作
78 /
79
80 // 3.1 获取指定属性
81 try {
82 Field declaredField = class1.getDeclaredField(“name”);
83 System.out.println(declaredField); // private java.lang.String Worker.name
84 } catch (NoSuchFieldException e) {
85 e.printStackTrace();
86 } catch (SecurityException e) {
87 e.printStackTrace();
88 }
89
90 // 3.2 获取所有属性
91 Field[] declaredFields = class1.getDeclaredFields();
92 for (Field field : declaredFields) {
93 System.out.println(field);
94 // private java.lang.Integer Worker.id
95 // private java.lang.String Worker.name
96 // java.lang.Integer Worker.age
97 }
98
99
100 /
*
101 * 4. 类中构造方法相关操作
102 /
103
104 // 4.1 获取参数列表匹配的构造方法
105 try {
106 Constructor declaredConstructor = class1.getDeclaredConstructor(Integer.class, String.class, Integer.class);
107 System.out.println(declaredConstructor); // private Worker(java.lang.Integer,java.lang.String,java.lang.Integer)
108 System.out.println(class1.getDeclaredConstructor(String.class)); // public Worker(java.lang.String)
109 } catch (NoSuchMethodException e) {
110 e.printStackTrace();
111 } catch (SecurityException e) {
112 e.printStackTrace();
113 }
114
115 // 4.2 获取类中所有公共构造方法
116 Constructor<?>[] constructors = class1.getConstructors();
117 for (Constructor<?> constructor : constructors) {
118 System.out.println(constructor);
119 // public Worker(java.lang.String)
120 // public Worker()
121 }
122
123 // 4.3 获取类中所有构造方法
124 Constructor<?>[] declaredConstructors = class1.getDeclaredConstructors();
125 for (Constructor<?> constructor : declaredConstructors) {
126 System.out.println(constructor);
127 // private Worker(java.lang.Integer,java.lang.String,java.lang.Integer)
128 // protected Worker(java.lang.Integer,java.lang.String)
129 // public Worker(java.lang.String)
130 // public Worker()
131 }
132
133 /
*
134 * 5. 类中方法相关操作
135 */
136
137 // 5.1 获取方法名和参数列表都匹配的方法
138 try {
139 Method declaredMethod = class1.getDeclaredMethod(“toString”);
140 System.out.println(declaredMethod); // public java.lang.String Worker.toString()
141 System.out.println(class1.getDeclaredMethod(“test”)); // //private void Worker.test()
142 } catch (NoSuchMethodException e) {
143 e.printStackTrace();
144 } catch (SecurityException e) {
145 e.printStackTrace();
146 }
147
148 // 5.2 获取类中所有公共方法
149 Method[] methods = class1.getMethods();
150 for (Method method : methods) {
151 System.out.println(method); // 当前类方法和它所继承的类及其实现的接口中的所有公共方法
152 }
153
154 // 5.3 获取当前类中所有方法
155 Method[] declaredMethods = class1.getDeclaredMethods();
156 for (Method method : declaredMethods) {
157 System.out.println(method);
158 // public java.lang.String Worker.toString()
159 // private void Worker.test()
160 }
161
162 }
163 }
164
165 复制代码

   3. 核心操作代码实现

1 import java.lang.reflect.Field;
2 import java.lang.reflect.Method;
3
4 class Worker {
5 // 私有属性
6 private Integer id;
7 private String name;
8 // 公共属性
9 public Integer age;
10
11 public Worker() {
12 }
13
14 @Override
15 public String toString() {
16 return “Worker [id=” + id + “, name=” + name + “, age=” + age + “]”;
17 }
18
19 // 私有方法
20 private void test() {
21 System.out.println(“这是私有方法”);
22 }
23
24 // 公共方法
25 public void show() {
26 System.out.println(“这是公共方法”);
27 }
28 }
29
30 public class TestReflect {
31 public static void main(String[] args) throws Exception {
32 // 1. 创建Class对象
33 Class<?> class1 = Class.forName(“Worker”);
34
35 // 2. 通过构造方法实例化类对象
36 Object obj = class1.getConstructor().newInstance();
37
38 // 3. 给公共属性设置值
39 Field field1 = class1.getField(“age”);
40 field1.set(obj, 18);
41
42 // 4. 给私有属性设置值
43 Field field = class1.getDeclaredField(“name”);
44 field.setAccessible(true); // 解除私有限定
45 field.set(obj, “张三”); // 为Worker类中的name属性设置值
46
47 // 5. 调用公共成员方法
48 Method method1 = class1.getMethod(“show”);
49 method1.invoke(obj);
50
51 // 6. 调用私有成员方法
52 Method method = class1.getDeclaredMethod(“test”);
53 method.setAccessible(true);
54 method.invoke(obj); // 第一个参数是类对象,其余的为实参
55 System.out.println(obj);
56 }
57 }

举报

相关推荐

0 条评论