• java3、异常


    一、异常

    Error:错误无法解决的问题。

    Exception:外部问题出现的异常

    常见的异常:空指针等等

    二、异常的处理(抓抛异常)

    处理方法一:try。。。catch。。。finally

    finally是可选的

    1. try{
    2. //可能出现的错误
    3. }catch(异常类型1 变量1){
    4. }catch(异常类型2 变量2){
    5. }....
    6. finally{
    7. //一定会执行的代码
    8. }

    从小往大写(否则报错),catch抓住了只会执行一次

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. String str ="abc";
    4. try {
    5. int num = Integer.parseInt(str);
    6. }catch (NumberFormatException e){
    7. System.out.println("出现异常了哦");
    8. e.printStackTrace();
    9. }
    10. System.out.println("hello");
    11. }
    12. }

    finally的使用:是可选的,及时catch中出现了错误,finally当中也要释放资源

    处理方式二:throws + 异常类型

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. try {
    4. fun();
    5. } catch (Exception e) {
    6. e.printStackTrace();
    7. }
    8. }
    9. public static void fun() throws Exception{
    10. String str = "abc";
    11. int num = Integer.parseInt(str);
    12. System.out.println("hello");
    13. }
    14. }

    try...catch...finally真正将异常处理掉了

    throws方式只是将异常抛给调用者

    两个的选择:如果父类被重写的没有throws异常,则方法也不能用throws,如果子类有就用try  cathc捕获

    手动抛异常 :  throws new RuntimeException("传入是局部匹配") 

    三、多线程

    1.多线程创建的方式一

    1. 继承Thread类的子类
    2. 重写Thread类的run() ==>将要执行的操作写在run方法中
    3. 创建Thread类的子类的对象
    4. 通过此对象调用start()
    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. MyThread t1 = new MyThread();
    4. t1.start();
    5. for (int i = 0; i < 100; i++) {
    6. if (i % 2 == 0) {
    7. System.out.println("*"+i);
    8. }
    9. }
    10. }
    11. }
    12. class MyThread extends Thread{
    13. @Override
    14. public void run() {
    15. for (int i = 0; i < 100; i++) {
    16. if (i % 2 == 0) {
    17. System.out.println(i);
    18. }
    19. }
    20. }
    21. }

    注意我们不能直接调用run()方法,只能调用start()

    开启两次线程需要再实例化一次对象

    练习两个线程做其他的事情

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. MyThread1 t1 = new MyThread1();
    4. MyThread2 t2 = new MyThread2();
    5. t1.start();
    6. t2.start();
    7. }
    8. }
    9. class MyThread1 extends Thread{
    10. @Override
    11. public void run() {
    12. for (int i = 0; i < 100; i++) {
    13. if (i % 2 == 0) {
    14. System.out.println("Thread1 "+i);
    15. }
    16. }
    17. }
    18. }
    19. class MyThread2 extends Thread{
    20. @Override
    21. public void run() {
    22. for (int i = 0; i < 100; i++) {
    23. if (i % 2 != 0) {
    24. System.out.println("Thread2 "+i);
    25. }
    26. }
    27. }
    28. }

    常用方法:

    start():启动当前线程:调用当前的线程的run()

    run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中

    currentThread():静态方法,返回当前代码的线程

    getName():获取当前线程的名字

    setName():设置当前线程的名字

    yield():释放cpu的执行权

    join():在线程a中调用b的join(),此时线程a就进入阻塞状态,知道线程b执行完,a在执行

    sleep():让当前线程

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. MyThread1 t1 = new MyThread1();
    4. t1.setName("线程一");
    5. t1.start();
    6. //给主线程命名
    7. Thread.currentThread().setName("主线程");
    8. }
    9. }
    10. class MyThread1 extends Thread{
    11. @Override
    12. public void run() {
    13. for (int i = 0; i < 100; i++) {
    14. if (i % 2 == 0) {
    15. System.out.println("Thread1 "+i+Thread.currentThread().getName());
    16. }
    17. }
    18. }
    19. }
    1. class MyThread1 extends Thread{
    2. @Override
    3. public void run() {
    4. for (int i = 0; i < 100; i++) {
    5. if (i % 2 == 0) {
    6. System.out.println("Thread1 "+i+Thread.currentThread().getName());
    7. }
    8. if (i % 2 == 0) {
    9. this.yield();
    10. try {
    11. sleep(1000);
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. }
    15. }
    16. }
    17. }
    18. }

    线程的优先级

    1. MAX_PRIORITY:10
    2. MIN_PRIORITY:1
    3. NORM_PRIORITY:5 --->默认优先级

    t1.sePriority(Thread.MAX_PRIORITY) 设置优先级

    t1.getPriority():获取优先级

    高优先级抢占cpu的执行权高,但不是讲百分之百执行

    实现卖票案例,存在安全问题

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Window w1 = new Window();
    4. Window w2 = new Window();
    5. Window w3 = new Window();
    6. w1.setName("窗口1");
    7. w2.setName("窗口2");
    8. w3.setName("窗口3");
    9. w1.start();
    10. w2.start();
    11. w3.start();
    12. }
    13. }
    14. class Window extends Thread{
    15. private int ticket =100;
    16. @Override
    17. public void run() {
    18. while (true){
    19. if(ticket >0){
    20. System.out.println(getName()+" 票号为:" +ticket);
    21. ticket--;
    22. }else{
    23. break;
    24. }
    25. }
    26. }
    27. }

    三、创建多线程的方式二:实现Runnable接口

    1. 创建一个实现了Runnable接口
    2. 实现类去实现Runnable中的抽象方法:run()
    3. 创建实现类的对象
    4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
    5. 通过Thread类的对象调用start()
    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Window window = new Window();
    4. Thread w1 = new Thread(window);
    5. Thread w2 = new Thread(window);
    6. Thread w3 = new Thread(window);
    7. w1.setName("窗口1");
    8. w2.setName("窗口2");
    9. w3.setName("窗口");
    10. w1.start();
    11. w2.start();
    12. w3.start();
    13. }
    14. }
    15. class Window implements Runnable{
    16. private int tickets = 100;
    17. public void run() {
    18. while (true){
    19. if(tickets > 0 ){
    20. System.out.println(Thread.currentThread().getName()+"票号为:"+tickets);
    21. tickets--;
    22. }else{
    23. break;
    24. }
    25. }
    26. }
    27. }

    两个创建方式的区别:

    开发中常用:继承Runnable类的创建方式

    原因1:实现没有单继承的局限性,实现的方式更适合来处理多个线程共享数据的问题(不用static)

    线程的生命周期

    新建、就绪、运行、阻塞、死亡

    线程的同步(买票重复的解决)

    在java中通过同步机制,来解决线程安全问题

    1.解决实现接口Runnable的线程安全问题

    方式一:同步代码块

    1. //方式一
    2. syschronized(同步监视器){
    3. //需要被同步的方法
    4. }
    5. //操作共享数据的代码,即被称为需要被同步的代码
    6. //共享数据:多个线程操作的变量
    7. //同步监视器成为,锁,任何一个类都可以称为对象,所有线程需要共用一把锁
    8. //补充,可以考虑this,充当锁,但是要保证他是唯一的
    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Window window = new Window();
    4. Thread w1 = new Thread(window);
    5. Thread w2 = new Thread(window);
    6. Thread w3 = new Thread(window);
    7. w1.setName("窗口1");
    8. w2.setName("窗口2");
    9. w3.setName("窗口3");
    10. w1.start();
    11. w2.start();
    12. w3.start();
    13. }
    14. }
    15. class Window implements Runnable{
    16. private int tickets = 1000;
    17. Object object = new Object(); //一样的,唯一就可以
    18. Dog dog = new Dog(); //一样的,唯一就可以
    19. public void run() {
    20. while (true){
    21. synchronized (object){
    22. if(tickets > 0 ){
    23. System.out.println(Thread.currentThread().getName()+"票号为:"+tickets);
    24. tickets--;
    25. }else{
    26. break;
    27. }
    28. }
    29. }
    30. }
    31. }
    32. class Dog{
    33. }

    方式二、同步方法

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Window window = new Window();
    4. Thread w1 = new Thread(window);
    5. Thread w2 = new Thread(window);
    6. Thread w3 = new Thread(window);
    7. w1.setName("窗口1");
    8. w2.setName("窗口2");
    9. w3.setName("窗口3");
    10. w1.start();
    11. w2.start();
    12. w3.start();
    13. }
    14. }
    15. class Window implements Runnable {
    16. private int tickets = 1000;
    17. public void run() {
    18. while (true) {
    19. show();
    20. }
    21. }
    22. public synchronized void show() {
    23. if (tickets > 0) {
    24. System.out.println(Thread.currentThread().getName() + "票号为:" + tickets);
    25. tickets--;
    26. }
    27. }
    28. }

    方式三、lock锁

    1. 先实例化一个ReentrantLock 
    2. 前调用lock 后 使用  unlock解锁,手动启动lock,手动释放unlock
    1. import java.util.concurrent.locks.ReentrantLock;
    2. public class HelloWorld {
    3. public static void main(String[] args) {
    4. Window window = new Window();
    5. Thread w1 = new Thread(window);
    6. Thread w2 = new Thread(window);
    7. Thread w3 = new Thread(window);
    8. w1.setName("窗口1");
    9. w2.setName("窗口2");
    10. w3.setName("窗口3");
    11. w1.start();
    12. w2.start();
    13. w3.start();
    14. }
    15. }
    16. class Window implements Runnable {
    17. private ReentrantLock reentrantLock = new ReentrantLock();
    18. private int tickets = 100;
    19. public void run() {
    20. while (true) {
    21. reentrantLock.lock();
    22. if (tickets > 0) {
    23. System.out.println(Thread.currentThread().getName() + "票号为:" + tickets);
    24. tickets--;
    25. }
    26. reentrantLock.unlock();
    27. }
    28. }
    29. }

    顺序lock-->同步代码块-->同步方法

    线程的通信

    wait():一旦执行此方法,当前线程进入阻塞,并释放同步监视器

    notify():一旦执行此方法,就会唤醒wait的一个线程,优先级高的await就会被唤醒

    notifyAll():一旦执行此方法,所有await的线程都会被唤醒

    这些方法都必须使用在同步代码块或同步方法中。三个方法的调用者必须是同步代码块和同步监视器

    这三个方法定义在Object里面

    经典例题:生产者/消费者问题

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Clerk clerk = new Clerk();
    4. Producer p1 = new Producer(clerk);
    5. p1.setName("生产者1");
    6. Customer c1 = new Customer(clerk);
    7. c1.setName("消费者1");
    8. Customer c2 = new Customer(clerk);
    9. c2.setName("消费者2");
    10. p1.start();
    11. c1.start();
    12. c2.start();
    13. }
    14. }
    15. class Clerk{
    16. private int productCount = 0;
    17. // 生产产品
    18. public synchronized void produceProduct() {
    19. if(productCount < 20){
    20. productCount++;
    21. System.out.println(Thread.currentThread().getName()+":开始生产第"+productCount+"个产品");
    22. notify();
    23. }else{
    24. try {
    25. wait();
    26. } catch (InterruptedException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }
    31. public synchronized void consumeProduct() {
    32. if(productCount > 0){
    33. System.out.println(Thread.currentThread().getName()+":开始消费第"+productCount+"个产品");
    34. productCount--;
    35. notify();
    36. }else{
    37. try {
    38. wait();
    39. } catch (InterruptedException e) {
    40. e.printStackTrace();
    41. }
    42. }
    43. }
    44. }
    45. class Producer extends Thread{
    46. private Clerk clerk;
    47. public Producer(Clerk clerk){
    48. this.clerk= clerk;
    49. }
    50. @Override
    51. public void run() {
    52. System.out.println(getName()+":开始生产产品。。。。");
    53. while (true){
    54. try {
    55. Thread.sleep(1000);
    56. } catch (InterruptedException e) {
    57. e.printStackTrace();
    58. }
    59. clerk.produceProduct();
    60. }
    61. }
    62. }
    63. class Customer extends Thread{
    64. private Clerk clerk;
    65. public Customer(Clerk clerk){
    66. this.clerk= clerk;
    67. }
    68. @Override
    69. public void run() {
    70. System.out.println(getName()+":开始消费产品。。。。");
    71. while (true){
    72. try {
    73. Thread.sleep(1000);
    74. } catch (InterruptedException e) {
    75. e.printStackTrace();
    76. }
    77. clerk.consumeProduct();
    78. }
    79. }
    80. }

    三、创建多线程的方式 实现callable接口

    1. 创建一个实现Callable的实现类
    2. 实现call方法,将线程需要执行的操作声明在call()中
    3. 主线程创建Callable接口实现类的对象
    4. 将此Callable接口实现的对象作为传递到FutrueTask构造器中,创建Futuretask对象
    5. 将FutrueTask的对象作为参数传递到Thread构造类的构造器中,创建Thread对象,并调用start()
    6. 获取callable中call的返回值
    7. get()返回值即为FutrueTask构造器参数的实现类重写的call()的返回值。
    1. import java.util.concurrent.Callable;
    2. import java.util.concurrent.ExecutionException;
    3. import java.util.concurrent.FutureTask;
    4. public class HelloWorld {
    5. public static void main(String[] args) {
    6. NumThread numThread = new NumThread();
    7. FutureTask futureTask = new FutureTask(numThread);
    8. new Thread(futureTask).start();
    9. try {
    10. Object o = futureTask.get();
    11. System.out.println("返回值是"+o);
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. } catch (ExecutionException e) {
    15. e.printStackTrace();
    16. }
    17. }
    18. }
    19. class NumThread implements Callable{
    20. private int i = 0;
    21. public Object call() throws Exception {
    22. for (int j = 0; j < 100; j++) {
    23. System.out.println(i);
    24. i++;
    25. }
    26. return 123;
    27. }
    28. }

    四、创建线程的方法:线程池

    好处:1.提高响应速度,2、降低资源消耗、3,便于线程管理

    1. import java.util.concurrent.ExecutorService;
    2. import java.util.concurrent.Executors;
    3. class NumberThread implements Runnable{
    4. public void run() {
    5. for(int i = 0 ; i < 100; i ++ ){
    6. if(i%2 == 0){
    7. System.out.println(Thread.currentThread().getName()+":"+i);
    8. }
    9. }
    10. }
    11. }
    12. class NumberThread1 implements Runnable{
    13. public void run() {
    14. for(int i = 0 ; i < 100; i ++ ){
    15. if(i%2 == 0){
    16. System.out.println(Thread.currentThread().getName()+":"+i);
    17. }
    18. }
    19. }
    20. }
    21. public class HelloWorld {
    22. public static void main(String[] args) {
    23. // 创建固定的线程池
    24. ExecutorService service = Executors.newFixedThreadPool(10);
    25. service.execute(new NumberThread()); //适合使用Runnable
    26. service.execute(new NumberThread1()); //适合使用Runnable
    27. //service.submit(); //适合使用Callable
    28. // 关闭连接池
    29. service.shutdown();
    30. }
    31. }

    五、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

    1. System.currentTimeMillis(); 返回时间戳
    2. Date date = new Date()   date.toString():显示当前的年月日   date.getTime()获取时间戳
    3. 获取指定时间 new Date(传入时间戳)  返回的时间

    SimpleDateFormat类

    1. SimpleDateFormat的实例化   SimpleDateFormat s = new SimpleDateFormat()    s.format(new Date()) 
    2. 逆过程:s = "19-12-18 上午11:43"  s.parse(str)
    3. 格式化  SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") 

    Calendar(日历)类

    查文档

    LocalDate、LocalTime、localDateTime

    查文档

    Instant

    查文档

    DateTimeFormatter(格式化时间)

    查文档

    比较器

    Arrays.sort(arr) 可以进行排序

    1. import java.util.Arrays;
    2. public class HelloWorld {
    3. public static void main(String[] args) {
    4. String[] arr = new String[]{"AA","CC","LL","DD","EE"};
    5. Arrays.sort(arr);
    6. System.out.println(Arrays.toString(arr));
    7. }
    8. } //[AA, CC, DD, EE, LL]

    Arrays.sort()排列自定义的类

    实现接口comparable 重写 comparator的方法  自然排序

    1. import java.lang.reflect.Array;
    2. import java.util.Arrays;
    3. public class HelloWorld {
    4. public static void main(String[] args) {
    5. Goods[] arr = new Goods[5];
    6. arr[0] = new Goods("lenoveMouse",35);
    7. arr[1] = new Goods("dellMouse",98);
    8. arr[2] = new Goods("xiaomiMouse",89);
    9. arr[3] = new Goods("huaweiMouse",67);
    10. arr[4] = new Goods("microsoftMouse",43);
    11. Arrays.sort(arr);
    12. for (int i = 0; i < arr.length; i++) {
    13. System.out.println(arr[i].toString());
    14. }
    15. }
    16. }
    17. class Goods implements Comparable{
    18. private String name;
    19. private double price;
    20. public Goods(){
    21. }
    22. public Goods(String name,double price){
    23. this.name = name;
    24. this.price = price;
    25. }
    26. @Override
    27. public String toString() {
    28. return "Goods{" +
    29. "name='" + name + '\'' +
    30. ", price=" + price +
    31. '}';
    32. }
    33. public int compareTo(Object o) {
    34. if( o instanceof Goods){
    35. Goods goods = (Goods) o;
    36. //方式一:
    37. if(this.price >goods.price ){
    38. return 1;
    39. }else if(this.price < goods.price){
    40. return -1;
    41. }else{
    42. return 0;
    43. }
    44. //方式二:
    45. // return Double.compare(this.price,goods.price);
    46. }
    47. // return 0;
    48. throw new RuntimeException("传入的数据不一致");
    49. }
    50. }

    comparator接口的使用:定制排序

    1. import java.util.Arrays;
    2. import java.util.Comparator;
    3. public class HelloWorld {
    4. public static void main(String[] args) {
    5. String[] arr = new String[]{"AA","DD","EE","CC","BB"};
    6. Arrays.sort(arr,new Comparator(){
    7. public int compare(Object o1, Object o2) {
    8. if(o1 instanceof String&&o2 instanceof String){
    9. String s1 = (String) o1;
    10. String s2 = (String) o2;
    11. return -s1.compareTo(s2);
    12. }
    13. throw new RuntimeException("输入的数据类型不一致");
    14. }
    15. });
    16. System.out.println(Arrays.toString(arr)); //[EE, DD, CC, BB, AA]
    17. }
    18. }

    自定义的类

    1. import java.lang.reflect.Array;
    2. import java.util.Arrays;
    3. import java.util.Comparator;
    4. public class HelloWorld {
    5. public static void main(String[] args) {
    6. Goods[] arr = new Goods[5];
    7. arr[0] = new Goods("lenoveMouse", 35);
    8. arr[1] = new Goods("dellMouse", 98);
    9. arr[2] = new Goods("xiaomiMouse", 89);
    10. arr[3] = new Goods("huaweiMouse", 67);
    11. arr[4] = new Goods("microsoftMouse", 43);
    12. Arrays.sort(arr, new Comparator() {
    13. //指明商品比较大小的方式:按照产品名称从高到低排序,在按价格从高到底
    14. public int compare(Object o1, Object o2) {
    15. if (o1 instanceof Goods && o2 instanceof Goods){
    16. Goods g1 = (Goods) o1;
    17. Goods g2 = (Goods) o2;
    18. if(g1.getName().equals(g2.getName())){
    19. return -Double.compare(g1.getPrice(), g2.getPrice());
    20. }else{
    21. return g1.getName().compareTo(g2.getName());
    22. }
    23. }
    24. throw new RuntimeException("数据输入有误");
    25. }
    26. });
    27. for (int i = 0; i < arr.length; i++) {
    28. System.out.println(arr[i].toString());
    29. }
    30. }
    31. }
    32. class Goods implements Comparable {
    33. private String name;
    34. private double price;
    35. public Goods() {
    36. }
    37. public Goods(String name, double price) {
    38. this.name = name;
    39. this.price = price;
    40. }
    41. public String getName() {
    42. return name;
    43. }
    44. public void setName(String name) {
    45. this.name = name;
    46. }
    47. public double getPrice() {
    48. return price;
    49. }
    50. public void setPrice(double price) {
    51. this.price = price;
    52. }
    53. @Override
    54. public String toString() {
    55. return "Goods{" +
    56. "name='" + name + '\'' +
    57. ", price=" + price +
    58. '}';
    59. }
    60. public int compareTo(Object o) {
    61. if (o instanceof Goods) {
    62. Goods goods = (Goods) o;
    63. //方式一:
    64. if (this.price > goods.price) {
    65. return 1;
    66. } else if (this.price < goods.price) {
    67. return -1;
    68. } else {
    69. return 0;
    70. }
    71. //方式二:
    72. // return Double.compare(this.price,goods.price);
    73. }
    74. // return 0;
    75. throw new RuntimeException("传入的数据不一致");
    76. }
    77. }

    System系统类 查文档

    Math数学类

     BigInteger与BigDecimal  查文档

    枚举类

    当需要定义许多常量就用枚举

    jdk:5.0之前:自定义枚举类

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Season spring = Season.Spring;
    4. System.out.println(spring);
    5. }
    6. }
    7. class Season{
    8. // 1.声明Season对象的属性:private final 修饰
    9. private final String seasonName;
    10. private final String seasonDesc;
    11. // 2.私有化构造器,并给属性赋值
    12. private Season(String seasonName,String seasonDesc){
    13. this.seasonName = seasonName;
    14. this.seasonDesc = seasonDesc;
    15. }
    16. // 3/提供当前类的多个对象:public static final的
    17. public static final Season Spring = new Season("春天","春意盎然");
    18. public static final Season SUMMER = new Season("夏天","夏日炎炎");
    19. public static final Season AUTUMN = new Season("秋天","秋高气爽");
    20. public static final Season WINTER = new Season("冬天","冰天雪地");
    21. public String getSeasonName() {
    22. return seasonName;
    23. }
    24. public String getSeasonDesc() {
    25. return seasonDesc;
    26. }
    27. @Override
    28. public String toString() {
    29. return "Season{" +
    30. "seasonName='" + seasonName + '\'' +
    31. ", seasonDesc='" + seasonDesc + '\'' +
    32. '}';
    33. }
    34. }

    jdk:5.0之后:enum

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Season spring = Season.Spring;
    4. System.out.println(spring);
    5. }
    6. }
    7. enum Season {
    8. Spring("春天", "春意盎然"),
    9. SUMMER("夏天", "夏日炎炎"),
    10. AUTUMN("秋天", "秋高气爽"),
    11. WINTER("冬天", "冰天雪地");
    12. // 1.声明Season对象的属性:private final 修饰
    13. private final String seasonName;
    14. private final String seasonDesc;
    15. // 2.私有化构造器,并给属性赋值
    16. private Season(String seasonName, String seasonDesc) {
    17. this.seasonName = seasonName;
    18. this.seasonDesc = seasonDesc;
    19. }
    20. }

    注解

    @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:

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Collection cl = new ArrayList();
    4. cl.add("123");
    5. cl.add("456");
    6. cl.add("789");
    7. cl.add("098");
    8. cl.add("765");
    9. Iterator iterator = cl.iterator();
    10. while (iterator.hasNext()){
    11. System.out.println(iterator.next());
    12. }
    13. }
    14. }

    foreach循环遍历

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Collection cl = new ArrayList();
    4. cl.add("123");
    5. cl.add("456");
    6. cl.add("789");
    7. cl.add("098");
    8. cl.add("765");
    9. for (Object obj : cl){
    10. System.out.println(obj);
    11. }
    12. }
    13. }

    foreach遍历数组

    1. int[] arr = new int[]{1,2,3,4,5,6};
    2. for (int i : arr){
    3. System.out.println(i);
    4. }

    Collection的子接口List

    ArrayList LinkedList   Vector

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. ArrayList arrayList = new ArrayList();
    4. arrayList.add(123);
    5. arrayList.add(456);
    6. arrayList.add("abc");
    7. arrayList.add(new Date());
    8. System.out.println(arrayList);
    9. // arrayList.add(int index,Collection eles);从index处开始添加元素
    10. System.out.println(arrayList.get(1)); //获取某个索引的值
    11. System.out.println(arrayList.indexOf(456)); //返回第一个出现这个的位置
    12. System.out.println(arrayList.lastIndexOf(456));//返回最后出现这个的位置
    13. // arrayList.remove(1) 删除索引
    14. // arrayList.set(int index,value) 设置某个索引的值
    15. // System.out.println(arrayList.subList(1,3)); 返回区间的值
    16. }
    17. }

    Set结构

    HashSet

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Set set = new HashSet();
    4. set.add(123);
    5. set.add(456);
    6. set.add("AA");
    7. set.add(new Date());
    8. }
    9. }

    HashLinked

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Set set = new LinkedHashSet(); //效率比hashSet高
    4. set.add(123);
    5. set.add(456);
    6. set.add("AA");
    7. set.add(new Date());
    8. }
    9. }

    TreeSet

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. Set set = new TreeSet(); //效率比hashSet高
    4. set.add(123);
    5. set.add(456);
    6. set.add("AA");
    7. set.add(new Date());
    8. System.out.println(set.size());
    9. }
    10. }

    Map接口

    map中的key:无序的、不可重复的、使用Set存储所有的key。value是无序的,可重复的,使用Collection存储所有value

    HashMap:效率高,频繁操作使用LinkedHashMap

    TreeMap

    HashTable(不用了)  Properties(处理属性文件)

    1. import java.util.HashMap;
    2. import java.util.Map;
    3. public class HelloWorld {
    4. public static void main(String[] args) {
    5. Map map1 = new HashMap();
    6. map1.put("BB",789);
    7. Map map = new HashMap();
    8. map.put("AA",123); //添加一个元素
    9. map.put("AA",456); //修改一个元素
    10. map.putAll(map1); //添加一个map
    11. map.remove("AA");//移除一个元素
    12. // map.clear(); //清除
    13. map.size();//返回大小
    14. map.get("BB");//获取指定key的值
    15. map.containsKey("BB");//是否包含这个key值
    16. map.containsValue(123);//是否包含这个Value值
    17. map.isEmpty();//判断是否为空
    18. }
    19. }

    遍历

    1. import java.util.*;
    2. public class HelloWorld {
    3. public static void main(String[] args) {
    4. Map map = new HashMap();
    5. map.put("AA",123);
    6. map.put("BB",789);
    7. map.put("CC",456);
    8. map.put("DD",901);
    9. //遍历所有的key集:keySet()
    10. Set set = map.keySet();
    11. Iterator iterator = set.iterator();
    12. while (iterator.hasNext()){
    13. System.out.println(iterator.next());
    14. }
    15. //遍历所有的Value值
    16. Collection values = map.values();
    17. for (Object o : values){
    18. System.out.println(o);
    19. }
    20. //遍历所有的Key-Value值
    21. Set entrySet = map.entrySet();
    22. Iterator iterator1 = entrySet.iterator();
    23. while (iterator1.hasNext()){
    24. Object o = iterator1.next();
    25. Map.Entry entry =(Map.Entry) o;
    26. System.out.println(entry.getKey()+"===>"+entry.getValue());
    27. }
    28. }
    29. }

    TreeMap

    1. Map map = new TreeMap();
    2. map.put("AA",123);
    3. map.put("BB",789);
    4. map.put("CC",456);
    5. map.put("DD",901); //可以实现排序

    Properties pros = new Properties(); 配置文件属性

    工具类

    1. import java.util.*;
    2. public class HelloWorld {
    3. public static void main(String[] args) {
    4. List list = new ArrayList();
    5. list.add(123);
    6. list.add(43);
    7. list.add(-89);
    8. list.add(0);
    9. System.out.println(list);
    10. // Collections.reverse(list); //反转
    11. // Collections.shuffle(list); //排序
    12. // Collections.sort(list); //排序
    13. Collections.swap(list,1,2);
    14. // 返回线程安全的List
    15. List list1 = Collections.synchronizedList(list);
    16. System.out.println(list1);
    17. }
    18. }

    泛型

    泛型用于检查,编译时保证数据的安全

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. ArrayList list = new ArrayList();
    4. list.add(123);
    5. list.add(456);
    6. Map map = new HashMap();
    7. map.put("A",123);
    8. // 泛型的嵌套
    9. Set> entry = map.entrySet();
    10. }
    11. }

    自定义泛型类

    多个多个用逗号隔开

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. // 如果定义了泛型类,但是没有使用则是Object,如果使用了泛型,那么就要用上
    4. Order order = new Order();
    5. // 建议实例化时指明泛型
    6. Order order1 = new Order("orderAA",1001,"order:AA");
    7. // order1.setOrderT(); String
    8. SubOrder subOrder = new SubOrder();
    9. // subOrder.setOrderT(); //integer
    10. }
    11. }
    12. //自定义泛型类
    13. class Order {
    14. String orderName;
    15. int orderId;
    16. // 类的内部结构就可以使用类的泛型
    17. T orderT;
    18. public Order() {
    19. }
    20. public Order(String orderName, int orderId, T orderT) {
    21. this.orderName = orderName;
    22. this.orderId = orderId;
    23. this.orderT = orderT;
    24. }
    25. public T getOrderT() {
    26. return orderT;
    27. }
    28. public void setOrderT(T orderT) {
    29. this.orderT = orderT;
    30. }
    31. }
    32. class SubOrder extends Order{
    33. }

    自定义泛型方法:查文档

    泛型通配符::通配符:?

    1. public class HelloWorld {
    2. public static void main(String[] args) {
    3. List list1 = null;
    4. List list2 = null;
    5. List list = null;
    6. }
    7. }
    8. IO流

      File类

      1. package com.baidu.exer;
      2. import java.io.File;
      3. import java.io.IOException;
      4. public class FileHello {
      5. public static void main(String[] args) throws IOException {
      6. // 常用方法
      7. // File file1 = new File("hello.txt");
      8. File file1 = new File("D:\\javaSE最新代码\\File\\File\\src\\hello.txt"); //绝对路径
      9. System.out.println(file1.getAbsoluteFile()); //获取绝对路径
      10. System.out.println(file1.getPath()); //获取路径
      11. System.out.println(file1.getName()); //获取名称
      12. System.out.println(file1.getParent());//获取上层目录路径
      13. System.out.println(file1.length()); //获取文件长度
      14. System.out.println(file1.lastModified());//获取最后一次修改时间
      15. System.out.println(file1.list());//获取数组名称
      16. System.out.println(file1.listFiles());//获取所哟名称
      17. System.out.println(file1.isFile());//判断是否是文件
      18. System.out.println(file1.isDirectory());//判断是否是文件
      19. System.out.println(file1.exists());//判断是否存在
      20. System.out.println(file1.canRead());//判断是否可读
      21. System.out.println(file1.canWrite());//判断是否可写
      22. System.out.println(file1.isHidden());//判断是否隐藏
      23. //创建功能方法
      24. File file3 = new File("h1.txt");
      25. if(!file3.exists()){
      26. file3.createNewFile();//创建文件
      27. System.out.println("创建成功");
      28. }else{
      29. file3.delete();//删除文件
      30. System.out.println("删除成功");
      31. }
      32. //文件目录的创建
      33. File file4 = new File("D:\\javaSE最新代码\\File\\File\\src\\hah");
      34. boolean mkdir = file4.mkdir();//创建目录
      35. if (mkdir){
      36. System.out.println("创建目录成功");
      37. }
      38. //文件目录的多级创建
      39. File file5 = new File("D:\\javaSE最新代码\\File\\File\\src\\heh\\he");
      40. boolean mkdirs = file4.mkdirs();//创建目录
      41. if (mkdirs){
      42. System.out.println("创建多级目录成功");
      43. }
      44. }
      45. }

       IO流的使用

      主方法文件位置相当于src

      普通方法文件位置相当于model

      结论:1.对于文本文件(.txt,.java,.c,.cpp)使用字符流处理

      2.对于非文本文件(.avi.map3)使用字节流处理

      读取数据的操作 FileReader

      1. package com.baidu.exer;
      2. import java.io.File;
      3. import java.io.FileReader;
      4. import java.io.IOException;
      5. public class FileHello {
      6. public static void main(String[] args) {
      7. /*流的分类
      8. 1.操作数据单位:字节流、字符流
      9. 2.数据的流向:输入流、输出流
      10. 3.流的角色:节点流、处理流
      11. 二、流的体系
      12. 抽象基类 节点流 缓冲流
      13. InputStream FileInputStream BufferedFileInputStream
      14. OutputStream FileOutputStream BufferedFileOutputStream
      15. Reader FileReader BufferedFileReader
      16. Writer FileWriter BufferedFileWriter
      17. */
      18. /*
      19. * 1.read()的理解:返回读取的一个字符,如果达到文件末尾返回-1
      20. * 2.异常处理用try—catch-finally处理
      21. * 3.要读入的文件一定要存在否则会报错
      22. * */
      23. //读取硬盘文件,并输出到控制台
      24. FileReader fr = null;
      25. try {
      26. // 1.实例化File类的对象,指明要操作的文件
      27. File file = new File("h1.txt");
      28. // 2.提供具体的流
      29. fr = new FileReader(file);
      30. // 3.数据的读入
      31. int data = fr.read();
      32. while (data != -1) {
      33. System.out.print((char) data);
      34. data = fr.read(); //相当于i++,没有了就返回-1
      35. }
      36. } catch (IOException e) {
      37. e.printStackTrace();
      38. } finally {
      39. // 4.流的关闭
      40. try {
      41. if (fr != null)
      42. fr.close();
      43. } catch (IOException e) {
      44. e.printStackTrace();
      45. }
      46. }
      47. }
      48. }

      对FileRead(上面)的升级read()的优化

      ctrl+alt+z:实现方法哦

      1. public class FileHello {
      2. public static void main(String[] args) {
      3. FileReader fr = null;
      4. try {
      5. //1.File类的实例化
      6. File file = new File("h1.txt");
      7. //2.FileReader流的实例化
      8. fr = new FileReader(file);
      9. //3.读入的操作
      10. //read(char[] cubf):返回每次读入cbuf数组中字符的个数。如果达到文件某位,返回-1
      11. char[] cbuf = new char[5];
      12. int len;
      13. while ((len = fr.read(cbuf)) != -1) {
      14. //方式一
      15. //for (int i = 0; i < len; i++) {
      16. // System.out.print(cbuf[i]);
      17. //}
      18. //方式二
      19. String str = new String()
      20. }
      21. } catch (IOException e) {
      22. e.printStackTrace();
      23. } finally {
      24. try {
      25. //4.资源的关闭
      26. if (fr != null)
      27. fr.close();
      28. } catch (IOException e) {
      29. e.printStackTrace();
      30. }
      31. }
      32. }
      33. }

      从内存中写出数据到硬盘

      1. package com.baidu.exer;
      2. import java.io.File;
      3. import java.io.FileReader;
      4. import java.io.FileWriter;
      5. import java.io.IOException;
      6. public class FileHello {
      7. public static void main(String[] args) {
      8. //输出操作,对应的文件可以不存在
      9. //如果不存在,会自动创建这个文件
      10. //如果存在,会被覆盖
      11. FileWriter fw = null;
      12. try {
      13. //1.File类的实例化
      14. File file = new File("h1.txt");
      15. //2.FileReader流的实例化
      16. //第一参数为文件,第二个参数为是否追加,true追加,false覆盖
      17. fw = new FileWriter(file,true);
      18. //3.写入的操作
      19. fw.write("I have a dream");
      20. } catch (IOException e) {
      21. e.printStackTrace();
      22. } finally {
      23. try {
      24. //4.资源的关闭
      25. if (fw != null)
      26. fw.close();
      27. } catch (IOException e) {
      28. e.printStackTrace();
      29. }
      30. }
      31. }
      32. }

      字符流不能处理图片(FileRead与FileWrite不可以)

      FileInputStream(读) FileOutStream(写)

      1. public class FileHello {
      2. public static void main(String[] args) {
      3. FileInputStream fis = null;
      4. try {
      5. //1.File类的实例化
      6. File file = new File("h1.txt");
      7. //2.FileReader流的实例化
      8. //第一参数为文件,第二个参数为是否追加,true追加,false覆盖
      9. fis = new FileInputStream(file);
      10. //3.写入的操作
      11. int len;
      12. byte[] buffer = new byte[5];
      13. while ((len = fis.read(buffer)) != -1){
      14. String str = new String(buffer,0,len);
      15. System.out.println(str);
      16. }
      17. } catch (IOException e) {
      18. e.printStackTrace();
      19. } finally {
      20. try {
      21. //4.资源的关闭
      22. if (fis != null)
      23. fis.close();
      24. } catch (IOException e) {
      25. e.printStackTrace();
      26. }
      27. }
      28. }
      29. }

      实现图片的复制

      1. public class FileHello {
      2. public static void main(String[] args) {
      3. FileOutputStream fos = null;
      4. FileInputStream fis = null;
      5. try {
      6. File srcFile = new File("hah.png");
      7. File destFile = new File("hah(1).png");
      8. fis = new FileInputStream(srcFile);
      9. fos = new FileOutputStream(destFile);
      10. byte[] buffer = new byte[1024];
      11. int len;
      12. while ((len = fis.read(buffer)) != -1) {
      13. fos.write(buffer, 0, len);
      14. }
      15. } catch (IOException e) {
      16. e.printStackTrace();
      17. } finally {
      18. try {
      19. fos.close();
      20. } catch (IOException e) {
      21. e.printStackTrace();
      22. }
      23. try {
      24. fis.close();
      25. } catch (IOException e) {
      26. e.printStackTrace();
      27. }
      28. }
      29. }
      30. }

      缓冲流的使用

      bos.flush()刷新缓冲区  BufferInputStream     BufferOutStream非文本

      1. package com.baidu.exer;
      2. import java.io.*;
      3. import java.util.Scanner;
      4. public class FileHello {
      5. public static void main(String[] args) {
      6. FileInputStream fis = null;
      7. FileOutputStream fos = null;
      8. BufferedInputStream bis = null;
      9. BufferedOutputStream bos = null;
      10. try {
      11. //1.造文件 实现非文本文件复制
      12. File srcFile = new File("h1.txt");
      13. File destFile = new File("h2.txt");
      14. //2.造流
      15. //2.1造节点流
      16. fis = new FileInputStream((srcFile));
      17. fos = new FileOutputStream(destFile);
      18. //2.2造缓冲流
      19. bis = new BufferedInputStream(fis);
      20. bos = new BufferedOutputStream(fos);
      21. //复制的细节读出与写入
      22. byte[] buffer = new byte[5];
      23. int len;
      24. while ((len = bis.read(buffer)) != -1){
      25. bos.write(buffer,0,len);
      26. }
      27. } catch (IOException e) {
      28. e.printStackTrace();
      29. } finally {
      30. //4.资源关闭:要求先关外面,再关里面
      31. // bos.close();
      32. // bis.close();
      33. //说明:关闭外流层的时候,内流层就会关闭,所以我们一般就关闭外面就可以
      34. try {
      35. fis.close();
      36. } catch (IOException e) {
      37. e.printStackTrace();
      38. }
      39. try {
      40. fos.close();
      41. } catch (IOException e) {
      42. e.printStackTrace();
      43. }
      44. }
      45. }
      46. }

      BufferRead与BufferWrier实现文本复制

      1. package com.baidu.exer;
      2. import java.io.*;
      3. import java.util.Scanner;
      4. public class FileHello {
      5. public static void main(String[] args) {
      6. BufferedReader br = null;
      7. BufferedWriter bw = null;
      8. try {
      9. //创建文件对应的流
      10. br = new BufferedReader(new FileReader(new File("h1.txt")));
      11. bw = new BufferedWriter(new FileWriter(new File("h3.txt")));
      12. //读写操作
      13. char[] cbuf = new char[5];
      14. int len;
      15. while ((len = br.read(cbuf)) != -1){
      16. bw.write(cbuf,0,len);
      17. }
      18. } catch (IOException e) {
      19. e.printStackTrace();
      20. } finally {
      21. //关闭资源
      22. try {
      23. bw.close();
      24. } catch (IOException e) {
      25. e.printStackTrace();
      26. }
      27. try {
      28. br.close();
      29. } catch (IOException e) {
      30. e.printStackTrace();
      31. }
      32. }
      33. }
      34. }

      转换流

      InputStreamReader:字节输入流到字符的输入流

      1. public class FileHello {
      2. // 任然应该使用try-catch-finally,偷个懒直接抛出去了
      3. public static void main(String[] args) throws IOException {
      4. FileInputStream fis = new FileInputStream("h1.txt");
      5. // InputStreamReader isr = new InputStreamReader(fis);//默认的字符集,jdk
      6. InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
      7. char[] cbuf = new char[5];
      8. int len;
      9. while ((len = isr.read(cbuf)) != -1){
      10. String str = new String(cbuf,0,len);
      11. System.out.print(str);
      12. }
      13. isr.close();
      14. }
      15. }

      结合使用 

      1. package com.baidu.exer;
      2. import java.io.*;
      3. import java.util.Scanner;
      4. public class FileHello {
      5. // 任然应该使用try-catch-finally,偷个懒直接抛出去了
      6. public static void main(String[] args) throws IOException {
      7. File file1 = new File("h1.txt");
      8. File file2 = new File("h4.txt");
      9. FileInputStream fis = new FileInputStream(file1);
      10. FileOutputStream fos = new FileOutputStream(file2);
      11. InputStreamReader isr = new InputStreamReader(fis);
      12. OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
      13. char[] cbuf = new char[3];
      14. int len;
      15. while ((len = isr.read(cbuf)) != -1){
      16. osw.write(cbuf,0,len);
      17. }
      18. isr.close();
      19. osw.close();
      20. }
      21. }

      对象流、将内存中的java对象保存到磁盘中通过网络传输出去使用objectpuStream实现

      1. public class FileHello {
      2. public static void main(String[] args) throws IOException, ClassNotFoundException {
      3. // 序列化:存入,内存放入到磁盘
      4. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
      5. oos.writeObject(new String("我爱天安门"));
      6. oos.flush();//操作刷新
      7. oos.close();
      8. //反序列化:读取,磁盘文件还原为内存
      9. ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
      10. Object obj = ois.readObject();
      11. String str = (String) obj;
      12. System.out.println(str);
      13. }
      14. }

      网络编程

      IP  InetAddress

      1. public class FileHello {
      2. public static void main(String[] args) {
      3. // ip地址,域名(www.baidu.com)、端口
      4. // 协议
      5. try {
      6. //实例化InetAddress
      7. InetAddress inet1 = InetAddress.getByName("192.168.137.1");
      8. System.out.println(inet1);
      9. InetAddress inet2 = InetAddress.getByName("www.aitguigu.com");
      10. System.out.println(inet2);
      11. InetAddress inet3 = InetAddress.getByName("127.0.0.1");
      12. System.out.println(inet3);
      13. //获取本地ip
      14. InetAddress inet4 = InetAddress.getLocalHost();
      15. System.out.println(inet4);
      16. //获取HostName
      17. System.out.println(inet4.getHostName());
      18. //获取InetAddress
      19. System.out.println(inet4.getAddress());
      20. } catch (UnknownHostException e) {
      21. e.printStackTrace();
      22. }
      23. }
      24. }

      实现TCP编程

      案例1:客户端发送内容给服务端,服务端将内容打印到控制台上。

      客户端代码:

      1. import java.io.*;
      2. import java.net.InetAddress;
      3. import java.net.ServerSocket;
      4. import java.net.Socket;
      5. public class code1 {
      6. public static void main(String[] args) {
      7. //客户端
      8. Socket socket = null;
      9. OutputStream os =null;
      10. try {
      11. InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
      12. socket = new Socket(inetAddress,8899);
      13. os = socket.getOutputStream();
      14. os.write("hello world,I have a dream".getBytes());
      15. System.out.println("发送成功");
      16. } catch (IOException e) {
      17. e.printStackTrace();
      18. }finally {
      19. try {
      20. socket.close();
      21. } catch (IOException e) {
      22. e.printStackTrace();
      23. }
      24. try {
      25. os.close();
      26. } catch (IOException e) {
      27. e.printStackTrace();
      28. }
      29. }
      30. }
      31. }

      服务段代码:

      1. package com.baidu.exer;
      2. import java.io.*;
      3. import java.net.InetAddress;
      4. import java.net.ServerSocket;
      5. import java.net.Socket;
      6. import java.net.UnknownHostException;
      7. import java.util.Scanner;
      8. public class FileHello {
      9. public static void main(String[] args) {
      10. //实现TCP编程
      11. ServerSocket ss = null;
      12. Socket socket = null;
      13. InputStream inputStream = null;
      14. ByteArrayOutputStream baos = null;
      15. try {
      16. //1.创建服务端的ServerSocket,指明自己的端口号
      17. ss = new ServerSocket(8899);
      18. //2.调用accept()表示接收来自于客户端的socket
      19. socket = ss.accept();
      20. //3.获取输入流
      21. inputStream = socket.getInputStream();
      22. //4.读取输入流中的数据
      23. // 不建议这样写有乱码
      24. // int len;
      25. // byte[] buffer = new byte[20];
      26. // while ((len=inputStream.read(buffer)) != -1){
      27. // String s = new String(buffer, 0, len);
      28. // System.out.print(s);
      29. // }
      30. baos = new ByteArrayOutputStream();
      31. byte[] buffer = new byte[5];
      32. int len;
      33. while ((len = inputStream.read(buffer)) != -1) {
      34. baos.write(buffer, 0, len);
      35. }
      36. System.out.println(baos.toString());
      37. } catch (IOException e) {
      38. e.printStackTrace();
      39. } finally {
      40. //5.关闭资源
      41. try {
      42. baos.close();
      43. } catch (IOException e) {
      44. e.printStackTrace();
      45. }
      46. try {
      47. inputStream.close();
      48. } catch (IOException e) {
      49. e.printStackTrace();
      50. }
      51. try {
      52. socket.close();
      53. } catch (IOException e) {
      54. e.printStackTrace();
      55. }
      56. try {
      57. ss.close();
      58. } catch (IOException e) {
      59. e.printStackTrace();
      60. }
      61. }
      62. }
      63. }

      案例二:客户端发送文件给服务端,服务端将数据保存在本地

      客户端:

      1. package com.baidu.exer;
      2. import java.io.*;
      3. import java.net.InetAddress;
      4. import java.net.ServerSocket;
      5. import java.net.Socket;
      6. public class FileHello {
      7. public static void main(String[] args) {
      8. Socket socket = null;
      9. OutputStream os = null;
      10. FileInputStream fis = null;
      11. try {
      12. socket = new Socket(InetAddress.getByName("127.0.0.1"), 8090);
      13. os = socket.getOutputStream();
      14. fis = new FileInputStream(new File("hah.png"));
      15. byte[] buffer = new byte[1024];
      16. int len;
      17. while ((len = fis.read(buffer)) != -1) {
      18. os.write(buffer, 0, len);
      19. }
      20. } catch (IOException e) {
      21. e.printStackTrace();
      22. } finally {
      23. try {
      24. fis.close();
      25. } catch (IOException e) {
      26. e.printStackTrace();
      27. }
      28. try {
      29. socket.close();
      30. } catch (IOException e) {
      31. e.printStackTrace();
      32. }
      33. try {
      34. os.close();
      35. } catch (IOException e) {
      36. e.printStackTrace();
      37. }
      38. }
      39. }
      40. }

      服务端:

      1. package com.baidu.exer2;
      2. import java.io.File;
      3. import java.io.FileOutputStream;
      4. import java.io.IOException;
      5. import java.io.InputStream;
      6. import java.net.ServerSocket;
      7. import java.net.Socket;
      8. public class Client {
      9. public static void main(String[] args) {
      10. //服务端
      11. ServerSocket ss = null;
      12. Socket socket = null;
      13. InputStream is = null;
      14. FileOutputStream fos = null;
      15. try {
      16. ss = new ServerSocket(8090);
      17. socket = ss.accept();
      18. is = socket.getInputStream();
      19. fos = new FileOutputStream(new File("hah2.png"));
      20. byte[] buffer = new byte[1024];
      21. int len;
      22. while ((len = is.read(buffer)) != -1) {
      23. fos.write(buffer,0,len);
      24. }
      25. } catch (IOException e) {
      26. e.printStackTrace();
      27. } finally {
      28. try {
      29. fos.close();
      30. } catch (IOException e) {
      31. e.printStackTrace();
      32. }
      33. try {
      34. is.close();
      35. } catch (IOException e) {
      36. e.printStackTrace();
      37. }
      38. try {
      39. socket.close();
      40. } catch (IOException e) {
      41. e.printStackTrace();
      42. }
      43. try {
      44. ss.close();
      45. } catch (IOException e) {
      46. e.printStackTrace();
      47. }
      48. }
      49. }
      50. }

      案例三:客户端给服务端发送数据成功后,服务端给客户端发送成功给客户端

      客户端:

      1. package com.baidu.exer;
      2. import java.io.*;
      3. import java.net.InetAddress;
      4. import java.net.ServerSocket;
      5. import java.net.Socket;
      6. public class FileHello {
      7. public static void main(String[] args) {
      8. Socket socket = null;
      9. OutputStream os = null;
      10. FileInputStream fis = null;
      11. try {
      12. socket = new Socket(InetAddress.getByName("127.0.0.1"), 8090);
      13. os = socket.getOutputStream();
      14. fis = new FileInputStream(new File("hah.png"));
      15. byte[] buffer = new byte[1024];
      16. int len;
      17. while ((len = fis.read(buffer)) != -1) {
      18. os.write(buffer, 0, len);
      19. }
      20. //接收来自服务端的数据,并显示到控制台
      21. InputStream is = socket.getInputStream();
      22. byte[] buffer1 = new byte[1024];
      23. int len1;
      24. while ((len1 = is.read(buffer1)) != -1) {
      25. System.out.println(buffer);
      26. System.out.println(new String(buffer1,len,1));
      27. }
      28. } catch (IOException e) {
      29. e.printStackTrace();
      30. } finally {
      31. try {
      32. fis.close();
      33. } catch (IOException e) {
      34. e.printStackTrace();
      35. }
      36. try {
      37. socket.close();
      38. } catch (IOException e) {
      39. e.printStackTrace();
      40. }
      41. try {
      42. os.close();
      43. } catch (IOException e) {
      44. e.printStackTrace();
      45. }
      46. }
      47. }
      48. }

      服务端:

      1. public static void main(String[] args) {
      2. //服务端
      3. ServerSocket ss = null;
      4. Socket socket = null;
      5. InputStream is = null;
      6. FileOutputStream fos = null;
      7. try {
      8. ss = new ServerSocket(8090);
      9. socket = ss.accept();
      10. is = socket.getInputStream();
      11. fos = new FileOutputStream(new File("hah3.png"));
      12. byte[] buffer = new byte[1024];
      13. int len;
      14. while ((len = is.read(buffer)) != -1) {
      15. fos.write(buffer,0,len);
      16. }
      17. //服务端给与客户端
      18. OutputStream os = socket.getOutputStream();
      19. os.write("你好,美女,照片我收到了很漂亮".getBytes());//发出信息
      20. } catch (IOException e) {
      21. e.printStackTrace();
      22. } finally {
      23. try {
      24. fos.close();
      25. } catch (IOException e) {
      26. e.printStackTrace();
      27. }
      28. try {
      29. is.close();
      30. } catch (IOException e) {
      31. e.printStackTrace();
      32. }
      33. try {
      34. socket.close();
      35. } catch (IOException e) {
      36. e.printStackTrace();
      37. }
      38. try {
      39. ss.close();
      40. } catch (IOException e) {
      41. e.printStackTrace();
      42. }
      43. }
      44. }

      UDP编程查文档了解一下

      URL编程查文档了解一下

    9. 相关阅读:
      Flutter 环境配置
      JMeter下载安装
      扩大WIFI覆盖范围用无线中继(WDS)
      jvm中的cms垃圾回收器和G1垃圾回收器有什么区别
      【蓝桥杯单片机】六、 PCF8591- DAC和DAC
      对称二叉树
      拖拽的使用说明
      Make.com实现多个APP应用的自动化的入门指南
      1 Getting Started with Database Administration
      用Powershell实现:删除所有不是与.json文件重名的.jpg文件
    10. 原文地址:https://blog.csdn.net/m0_61927991/article/details/126748664