当前位置: 首页 > news >正文

学习大数据,所需要Java基础(9)

文章目录

  • 网络编程
    • 实现简答客户端和服务器端的交互
      • 编写客户端
      • 编写服务端
    • 文件上传
      • 文件上传客户端以及服务器端实现
      • 文件上传服务器端实现(多线程)
      • 文件上传服务器端(连接池版本)
      • 关闭资源工具类
    • BS架构服务器案例
      • 案例分析
      • BS结构服务器代码实现
  • Junit单元测试
    • Junit介绍
    • Junit的基本使用(重点)
    • Junit的注意事项
    • Junit相关注解
    • @Test以后怎么使用
  • 类的加载时机
    • 类加载器(了解)_ClassLoader
  • 反射
    • class类的以及class对象的介绍以及反射介绍
    • 反射之获取class对象
      • 三种获取Class对象的方式最通用的一种
    • 获取Class对象中的构造方法
      • 获取所有public的构造对象
      • 获取空参构造_public
      • 利用空参构创建对象的快捷方式_public
      • 利用反射获取有参构造并创建对象_public

网络编程

实现简答客户端和服务器端的交互

相关介绍
在这里插入图片描述

编写客户端

1.创建Socket对象,指明连接服务器端的IP以及端口号
2.调用Socket中的getOutputStream方法,发送请求
3.调用Socket中的getInputStream方法,接收响应
4.关流

public class Client {public static void main(String[] args) throws IOException {
//        1.创建Socket对象,指明连接服务器端的IP以及端口号final Socket socket = new Socket("127.0.0.1",6666);
//        2.调用Socket中的getOutputStream方法,发送请求final OutputStream outputStream = socket.getOutputStream();outputStream.write("发送请求,请回应".getBytes(StandardCharsets.UTF_8));
//        3.调用Socket中的getInputStream方法,接收响应final InputStream inputStream = socket.getInputStream();final byte[] bytes = new byte[1024];int len = inputStream.read(bytes);System.out.println(new String(bytes,0,len));
//        4.关流inputStream.close();outputStream.close();}
}

编写服务端

1.创建ServerSocket。设置端口号
2.调用accept方法等待连接的客户端对象
3.调用socket中的getInputStream用于读取客户端发过来的请求
4.调用socket中的getOutputStream,用于给客户端响应结果
5.关流

public class Server {public static void main(String[] args) throws IOException {//创建ServerSocket,设置端口号final ServerSocket serverSocket = new ServerSocket(6666);//调用accept方法等待连接的客户端对象final Socket socket = serverSocket.accept();//调用socke中的getInputStream,用于读取客户端发过来的请求final InputStream inputStream = socket.getInputStream();final byte[] bytes = new byte[1024];final int read = inputStream.read(bytes);System.out.println(new String(bytes,0,read));//调用socket中的getOutputStream,用于给客户端相应结果final OutputStream outputStream = socket.getOutputStream();outputStream.write("给你资源,发送吧".getBytes(StandardCharsets.UTF_8));//关流inputStream.close();outputStream.close();socket.close();serverSocket.close();}
}

文件上传

在这里插入图片描述

文件上传客户端以及服务器端实现

客户端

public class Client {public static void main(String[] args) throws IOException {//创建socket对象final Socket socket = new Socket("127.0.0.1", 6666);//创建FileInputStream,将读取本地上的照片final FileInputStream fileInputStream = new FileInputStream("C:\\Users\\94863\\Pictures\\Saved Pictures\\hua.jpg");//调用getOutputStream,将读取过来的照片写到服务端final OutputStream outputStream = socket.getOutputStream();final byte[] bytes = new byte[1024];int len;while ((len = fileInputStream.read(bytes))!=-1){outputStream.write(bytes,0,len);}//给服务端写一个结束标志socket.shutdownOutput();System.out.println("==============以下是接收相应的代码=========================");//调用getInputStream,读取服务器端相应回来的数据final InputStream inputStream = socket.getInputStream();final byte[] bytes1 = new byte[1024];final int read = inputStream.read(bytes1);System.out.println(new String(bytes1,0,read));//关流inputStream.close();outputStream.close();fileInputStream.close();socket.close();}
}

服务器端

public class Server {public static void main(String[] args) throws IOException {//创建ServerSocket对象,设置端口号final ServerSocket serverSocket = new ServerSocket(6666);//调用accept方法,等待连接的客户端final Socket socket = serverSocket.accept();//调用getInputStream读取客户端发过来额照片final InputStream inputStream = socket.getInputStream();//创建FileOutStream,将读取过来的照片写到本地上final String name = System.currentTimeMillis() + "" + new Random().nextInt() + ".jpg";final FileOutputStream fileOutputStream = new FileOutputStream("D:\\Ajava\\"+name);final byte[] bytes = new byte[1024];int len;while ((len = inputStream.read(bytes))!=-1){fileOutputStream.write(bytes,0,len);}System.out.println("============以下代码为相应代码===================");//响应数据final OutputStream outputStream = socket.getOutputStream();outputStream.write("上传成功".getBytes(StandardCharsets.UTF_8));//关流outputStream.close();fileOutputStream.close();inputStream.close();socket.close();serverSocket.close();}
}

文件上传服务器端实现(多线程)

public class Server_muti {public static void main(String[] args) throws IOException {//创建ServerSocket对象,设置端口号final ServerSocket serverSocket = new ServerSocket(6666);while (true) {//调用accept方法,等待连接的客户端final Socket socket = serverSocket.accept();new Thread(new Runnable() {@Overridepublic void run() {final InputStream inputStream;try {//调用getInputStream读取客户端发过来额照片inputStream = socket.getInputStream();//创建FileOutStream,将读取过来的照片写到本地上final String name = System.currentTimeMillis() + "" + new Random().nextInt() + ".jpg";final FileOutputStream fileOutputStream = new FileOutputStream("D:\\Ajava\\" + name);final byte[] bytes = new byte[1024];int len;while ((len = inputStream.read(bytes)) != -1) {fileOutputStream.write(bytes, 0, len);}System.out.println("============以下代码为相应代码===================");//响应数据final OutputStream outputStream = socket.getOutputStream();outputStream.write("上传成功".getBytes(StandardCharsets.UTF_8));//关流outputStream.close();fileOutputStream.close();inputStream.close();socket.close();serverSocket.close();} catch (IOException e) {e.printStackTrace();}}}).start();}}}

文件上传服务器端(连接池版本)

public class Server_pools {public static void main(String[] args) throws IOException {//创建ServerSocket对象,设置端口号final ServerSocket serverSocket = new ServerSocket(6666);final ExecutorService executorService = Executors.newFixedThreadPool(10);while (true){//调用accept方法,等待连接的客户端final Socket socket = serverSocket.accept();executorService.submit(new Runnable() {@Overridepublic void run() {InputStream inputStream = null;FileOutputStream fileOutputStream = null;OutputStream outputStream = null;//调用getInputStream读取客户端发过来额照片try {inputStream = socket.getInputStream();//创建FileOutStream,将读取过来的照片写到本地上final String name = System.currentTimeMillis() + "" + new Random().nextInt() + ".jpg";fileOutputStream = new FileOutputStream("D:\\Ajava\\" + name);final byte[] bytes = new byte[1024];int len;while ((len = inputStream.read(bytes)) != -1) {fileOutputStream.write(bytes, 0, len);}System.out.println("============以下代码为相应代码===================");//响应数据outputStream = socket.getOutputStream();outputStream.write("上传成功".getBytes(StandardCharsets.UTF_8));//关流outputStream.close();fileOutputStream.close();inputStream.close();socket.close();} catch (IOException e) {e.printStackTrace();}}});}}
}

关闭资源工具类

我们创建一个工具类,以便快速关闭资源

public class CloseUtils {public  static void close(InputStream is, FileOutputStream fos, OutputStream os, Socket so){if (os != null){try {os.close();} catch (IOException e) {e.printStackTrace();}}if (fos != null){try {fos.close();} catch (IOException e) {e.printStackTrace();}}if (is != null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if (so != null){try {so.close();} catch (IOException e) {e.printStackTrace();}}}
}

BS架构服务器案例

在这里插入图片描述

案例分析

在这里插入图片描述

BS结构服务器代码实现

public class bstest {public static void main(String[] args) throws IOException {//创建ServerSocket对象final ServerSocket serverSocket = new ServerSocket(8888);while (true) {//调用accept方法接收客户端final Socket socket = serverSocket.accept();//调用getInputStream用于读取浏览器发过来的请求final InputStream inputStream = socket.getInputStream();/*1.描述:需要将is对象转成BufferedReader对象然后调用BufferedReader中的readLine方法读取请求信息第一行2.怎么将InputStream转成BufferedReader?只需要将InputStream想办法塞到BufferedReader的构造中即可3.BufferedReader构造:BufferedReader(Reader r)Reader是抽象类,需要传递子类,我们可以传递InputStreamReader而InputStreamReader的构造正好可以传递InputStream4.如何转:new BufferedReader(new InputStreamReader(InputStream is))*/final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String s = bufferedReader.readLine();String s2 = s.split(" ")[1];String path = s2.substring(1);//创建FileInputStream对象final FileInputStream fileInputStream = new FileInputStream(path);//调用getOutputStream 将读取到的html写到浏览器final OutputStream outputStream = socket.getOutputStream();//写相应信息给浏览器outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());outputStream.write("Content-Type:text/html\r\n".getBytes());outputStream.write("\r\n".getBytes());byte[] bytes = new byte[1024];int len;while ((len = fileInputStream.read(bytes)) != -1) {outputStream.write(bytes, 0, len);}//关流outputStream.close();fileInputStream.close();bufferedReader.close();inputStream.close();socket.close();}}}

Junit单元测试

Junit介绍

1.概述:单元测试 ,用于测试一个方法的,属于第三方工具,所以使用需要导jar包,在一定程度上可以代替main方法
2.作用:单独测试一个方法,看看此方法能不能跑通

Junit的基本使用(重点)

1.导包
2.在方法时写:@test
3.执行:
a.双击方法名,右键,点run
b.在方法的左边有一个绿色的小摁钮,点击它,点run

public class test01 {@Testpublic void add(){System.out.println("添加新功能");}@Testpublic void deltet(){System.out.println("删除功能");}
}

Junit的注意事项

1.静态方法不能使用@Test
2.带参数的方法不能使用@Test
3.带返回值的方法不能使用@Test

Junit相关注解

1.@Before:在@Test之前执行,有多少个@Test一起执行,@Before就执行多少次
2.@After:在@Test之后执行,有多少个@Test一起执行,@After就执行多少次
3.@Before:一般都用于初始化数据
@After:一般用于关闭资源

public class test01 {@Testpublic void add(){System.out.println("添加新功能");}@Testpublic void deltet(){System.out.println("删除功能");}@Testpublic void update(){System.out.println("修改功能");}@Beforepublic void before(){System.out.println("我是before功能");}@Afterpublic void after(){System.out.println("我是After功能");}
}

@Test以后怎么使用

对商品进行更删改查

public class CategoryImpl {public void add(String s){System.out.println("添加商品分类"+s);}public void delete(int id){System.out.println("id为" + id + "被删除");}public void update(int id){System.out.println("id为"+ id + "被修改");}
}
public class test02 {@Test//测试add功能public void add(){new CategoryImpl().add("服装");}@Test//测试删除功能public void delete(){new CategoryImpl().delete(0001);}
}

类的加载时机

1.new对象
2.new子类对象(new子类对象先初始化父类)
3.执行main方法
4.调用静态成员
5.利用反射反射这个类
在这里插入图片描述

类加载器(了解)_ClassLoader

1.概述:在jvm中,负责将本地上的class文件加载到内存的对象_ClassLoader
2.分类:
BootStrapClassLoader:根类加载器—》C语言写的,我们获取不到的也称之为引导类加载器,负载Java的核心类加载,比如
System,String等 jre/lib/rt.jar下的类都是核心类
ExtClassLoader:负责类加载器,负载jre的扩展目录中的jar包的加载,在jdk中jre的lib目录下的ext目录
AppClassLoader:系统类加载器,负责在居民启动时,加载来自java命令的class文件(自定义类)
以及classPath环境变量所指定的jar包(第三方jar包)
不同的类加载器负责加载不同的类
3.三者的关系:AppClassLoader的父类加载器时ExtClassLoader
ExtClassLoader的父类加载器时BootStrapClassLoader
但是:他们从代码级别上来看,没有子父类继承关系 ---- 他们都有一个共同的父类---- ClassLoader
4.获取类加载对象
类名.class.getClassLoader()
5.获取类加载器对象对应的父类加载器
ClassLoader类中的方法:ClassLoader
getParent() ----- 没啥用
6.双亲委派(全盘负责委托机制)
a.Person类中有一个String
Person本身是AppClassLoader加载
String是BootStrapClassLoader加载
b.加载顺序
Person本身是App加载,按道理来说String也是App加载,但是app加载String的时候,先询问Ext是否加载,Ext负责加载的是拓展类, 再询问boot是否加载,boot负责加载核心类,所以String被加载
再比如
a.Test是app加载,person按理来说也是app加载,但是app先问ext要不要加载
ext说不负责加载自定义类,我找boot去,boot一看,我不负责加载自定义类->perosn
app一看,两个爹都不加载,我自己加
b.结论:两个双亲都不加载,app才自己加载
比如:如果来了一个DNSNameService,我就想直接加载DNSNameService(扩展类),
本身ext要加载,但是先问boot,如果boot不加载,ext再加载
7.类加载器的cache(缓存)机制(拓展):一个类加载到内存之后,缓存中也会保存一份,后面如果在使用此类,如果缓存中保存了这个类,就直接返回他,如果没有才加载这个类,下一次如果有其他类在使用的时候就不会重新加载了,直接去缓存中拿,所以这就是为什么每个类只加载一次,内存只有一份的原因
8.所以,类加载器的双亲委派和缓存机制共同早就了加载类的特点,每个类只在内存中加载一次

public class test03 {public static void main(String[] args) {boot();ext();app();}public static void boot(){final ClassLoader classLoader = Integer.class.getClassLoader();System.out.println(classLoader);}public static void ext(){final ClassLoader classLoader = DNSNameService.class.getClassLoader();System.out.println("classLoader = " + classLoader);}public static void app(){final ClassLoader classLoader = test01.class.getClassLoader();System.out.println("classLoader = " + classLoader);}
}

反射

class类的以及class对象的介绍以及反射介绍

1.class对象:jvm在堆内存中为加载到内存中的class文件创建出来的对象
2.class类:描述这个class对象额类叫做class类
在这里插入图片描述

反射之获取class对象

1.方法1:new对象,调用Object中的方法 Class getClass()
2.方法2:不管是基本类型还是引用类型,都有一个静态成员class
3.方式3:class类中的方法 static Class<?> forName(String className)
className:类的全限定名 — 包名.类名

public class test04 {public static void main(String[] args) throws ClassNotFoundException {
//        1.方法1:new对象,调用Object中的方法  Class getClass()final Person person = new Person();Class class1 = person.getClass();System.out.println(class1);
//        2.方法2:不管是基本类型还是引用类型,都有一个静态成员classfinal Class<Person> personClass = Person.class;System.out.println(personClass);
//        3.方式3:class类中的方法    static Class<?> forName(String className)
//        className:类的全限定名  --- 包名.类名final Class<?> aClass = Class.forName("Unitexc.Person");System.out.println(aClass);}
}

三种获取Class对象的方式最通用的一种

1.Class.forName(“类的全限定名”)
2.原因:参数为String,可以配合配置文件使用

显然最后一种是常用的,我们进行代码事项,首先在相关包下,建立一个File名为pro.properties
内容为: className=Unitexc.Person

public class test05 {public static void main(String[] args) throws IOException, ClassNotFoundException {final Properties properties = new Properties();final Person person = new Person();final FileInputStream in = new FileInputStream("D:\\untitled7\\day21\\src\\pro.properties");properties.load(in);String className = properties.getProperty("className");//System.out.println(className);final Class<?> aClass = Class.forName(className);System.out.println(aClass);}
}

获取Class对象中的构造方法

获取所有public的构造对象

class类中的方法
Constructor<?>[] getConstructors() ----- 获取所有public的构造方法

public class test06 {public static void main(String[] args) {final Class<Person> personClass = Person.class;final Constructor<?>[] constructors = personClass.getConstructors();for (Constructor<?> constructor : constructors) {System.out.println(constructor);}}
}

获取空参构造_public

Class类中的方法
Constructor getConstructor(Class<?>… parameterTypes)
parameterTypes:是一个可变参数,可以传递0个或者多个参数,传递的是参数类型的class对象
如果获取空参构造,paramTypes不写了
如果获取有参构造,parameterTypes写参数类型的class对象
Constructor类中的方法
T newInstance(Object…initargs)----- 创建对象
initargs:是一个可变参数,可以传递0个或者多个参数,传递的是实参
如果根据空参构造创建对象,initargs不用写了
如果根据有参构造创建对象,initargs需要写实参

public class test07 {public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {final Class<Person> ac = Person.class;final Constructor<Person> constructor = ac.getConstructor();final Person person = constructor.newInstance();System.out.println(person);}
}

利用空参构创建对象的快捷方式_public

Class类中的方法
T newInstance() 根据空参构造new对象
前提:
被反射的类中必须又public的空参构造

final Person person1 = ac.newInstance();
System.out.println(person1);

利用反射获取有参构造并创建对象_public

Class类中的方法
Class类中的方法
Constructor getConstructor(Class<?>… parameterTypes)
parameterTypes:是一个可变参数,可以传递0个或者多个参数,传递的是参数类型的class对象
如果获取空参构造,paramTypes不写了
如果获取有参构造,parameterTypes写参数类型的class对象
Constructor类中的方法
T newInstance(Object…initargs)----- 创建对象
initargs:是一个可变参数,可以传递0个或者多个参数,传递的是实参
如果根据空参构造创建对象,initargs不用写了
如果根据有参构造创建对象,initargs需要写实参

final Class<Person> personClass = Person.class;final Constructor<Person> constructor = personClass.getConstructor(String.class,Integer.class);final Person li = constructor.newInstance("李云龙", 35);System.out.println(li);

相关文章:

  • taosdb快速入门
  • Docker的基本概念和优势
  • 【鸿蒙 HarmonyOS 4.0】常用组件:List/Grid/Tabs
  • 常见doc命令使用
  • 2024蓝桥杯每日一题(二分)
  • torchrun常见参数
  • 【论文阅读】ACM MM 2023 PatchBackdoor:不修改模型的深度神经网络后门攻击
  • 颜色检测python项目
  • xlsx.js读取本地文件,按行转成数组数据
  • 手机App防沉迷系统C卷(JavaPythonC++Node.jsC语言)
  • UE5.1_TimeLine
  • yudao-cloud 学习笔记
  • web服务,C/S框架,单设备登陆实现方案
  • C++中实现String类
  • mysqld.exe运行时,提示缺少msvcr100.dll,msvcp100.dll文件,导致mysql安装失败或mysql服务无法启动
  • IE9 : DOM Exception: INVALID_CHARACTER_ERR (5)
  • Android 架构优化~MVP 架构改造
  • Angular6错误 Service: No provider for Renderer2
  • Git初体验
  • HTTP中的ETag在移动客户端的应用
  • Java到底能干嘛?
  • Linux中的硬链接与软链接
  • Python中eval与exec的使用及区别
  • Spring-boot 启动时碰到的错误
  • Vue.js 移动端适配之 vw 解决方案
  • Webpack入门之遇到的那些坑,系列示例Demo
  • 包装类对象
  • 初识 beanstalkd
  • 初识MongoDB分片
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 对话:中国为什么有前途/ 写给中国的经济学
  • 反思总结然后整装待发
  • 技术:超级实用的电脑小技巧
  • 目录与文件属性:编写ls
  • 前嗅ForeSpider中数据浏览界面介绍
  • 如何胜任知名企业的商业数据分析师?
  • 深度学习在携程攻略社区的应用
  • 吐槽Javascript系列二:数组中的splice和slice方法
  • 微信开源mars源码分析1—上层samples分析
  • ​你们这样子,耽误我的工作进度怎么办?
  • # centos7下FFmpeg环境部署记录
  • #define与typedef区别
  • (2.2w字)前端单元测试之Jest详解篇
  • (八)Spring源码解析:Spring MVC
  • (第8天)保姆级 PL/SQL Developer 安装与配置
  • (二)换源+apt-get基础配置+搜狗拼音
  • (六)c52学习之旅-独立按键
  • (实战篇)如何缓存数据
  • (一)基于IDEA的JAVA基础1
  • (转)3D模板阴影原理
  • (转)linux 命令大全
  • **PyTorch月学习计划 - 第一周;第6-7天: 自动梯度(Autograd)**
  • .NET 使用 XPath 来读写 XML 文件
  • .net 使用ajax控件后如何调用前端脚本
  • .net知识和学习方法系列(二十一)CLR-枚举