<5>第五期

七、AVA反射
1.-反射的基本概念

一般情况下,我们知道一个类,那可以通过这个类创建对象;

但是如果要求通过一个对象找到一个类,这时候反射就派上用场了。

java反射实现的核心就是Class类 java.lang包下的。

2.java反射-java Class基本使用
// 这里对象.getClass() 调用的是Object类的getClass()
//得到Class对象 然后再调用Class里的getName()方法,获取到完整包路径类;
public class Test01 {
public static void main(String[] args) {
	 Student stu=new Student();
	System.out.println( stu.getClass().getName());
}
}
// 
public class Student {
	private String name;
	private Integer age;
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}	
}
//  
public class Test02 {
	public static void main(String[] args) {
		//通过完整包路径类型来实例化Class对象:
		        try {
		        	//此时需要用到泛型  光标放到对应class位置上,就可以看到所需的泛型一般通用符  ?
		        	Class<?> c=Class.forName("com.java1234_7.Student");
		        	System.out.println(c.getName()); 
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
		        
		    }
	}
//  
public class Test03 {
	public static void main(String[] args) {
		Class<?> c=null;
		 try {
	        //此时需要用到泛型  光标放到对应class位置上,就可以看到所需的泛型一般通用符  ?
	        c=Class.forName("com.java1234_7.Student");
	        System.out.println(c.getName()); 	
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		 // 因为返接收回的泛型,可以直接用Student
		 /**
		  * 此时访问的是Student的无参 
		  */
		 Student s=null;
			try {
				c.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		 s.setAge(23);
		 s.setName("sss");
		 System.out.println(s);
	}
}
//
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test04 {
	public static void main(String[] args) {
		Class<?> c=null;
        try {
            c=Class.forName("com.java1234_7.Student");  
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Student s=null;
        Constructor<?>[] cons=c.getConstructors();
        try {
            s=(Student) cons[0].newInstance("四史",68);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(s);
		 }
}

3.通过反射获取类的基本结构
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test05 {
	public static void main(String[] args) {
		Class<?> c=null;
        try {
            c=Class.forName("com.java1234_7.Student");  
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("---------------------------------------------");
        //获取所有构造方法
        //1.通过getConstructors()方法
        Constructor<?>[] cons= c.getConstructors();
        //增强for循环
        for(Constructor<?> con :cons){
        	System.out.println("构造方法:"+con);
        }
        System.out.println("--------------------------------------------");
        //2,通过getMethods()方法获取所有方法
        Method[]  mts= c.getMethods();
        for(Method m:mts){
        	System.out.println(m);
        }
        System.out.println("--------------------------------------------");
        // 3,通过getDeclaredFields()方法获取所有属性
        Field[] fd=c.getDeclaredFields();
        for(Field f:fd){
        	System.out.println(f);
        }
        
 }
}

4.通过反射调用方法和操作属性

1,通过反射调用方法,主要通过invoke方法

package com.java1234_7;

import java.lang.reflect.Method;

public class Test06 {
	public static void main(String[] args) {
		Class<?> c=null;
        try {
           c=Class.forName("com.java1234_7.Student");  
            //反射获取类所实现的所有接口用到
            c=Class.forName("com.java1234_7.Student2");  
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("---------------------------------------------");
        try {
		// 获取单个方法实现调用  getClass().getMethod()
		 Object obj=c.newInstance();
         Method m2=obj.getClass().getMethod("setName", String.class);
         m2.invoke(obj, "小锋");
         
         Method m=obj.getClass().getMethod("getName");
         String name=(String) m.invoke(obj);
         System.out.println("name="+name);
         
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

2,通过反射操作属性,java里反射可以操作私有属性,只需要设置下


import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test07 {
	public static void main(String[] args) {
		Class<?> c=null;
        try {
            //反射获取类所实现的所有接口用到
            c=Class.forName("com.java1234_7.Student2");  
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("---------------------------------------------");
        try {
		
		 Object obj=c.newInstance();
		 Field f1= c.getDeclaredField("name");
		 //反射提供的方法,可以去访问私有属性
		 f1.setAccessible(true);
		 f1.set(obj, "协商");
		 System.out.println(f1.get(obj));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

八、JAVA集合
1.集合的引入

方法接口祖先级别:Collection

在对数据进行操作时候,数组也可以,但是存在一些问题,数组必须先定义好长度,也就是数组的长度是固定,不能根据我们的需求自动变长或者变短。

假如我们定义一个长度为3的数组,此时已经存储了3个,再想加一个时候就比较麻烦,用集合就可以解决好这个问题。

2.List集合

Collection接口是集合的老祖宗

List接口的主要实现类有ArrayList,和LinkedList。

上才艺:具体那个方法的使用用api工具查询

ArrayList

import java.util.ArrayList;
public class TestArrayList {
	public static void print(ArrayList<String> arraylist){
		System.out.println("当前输出的元素:");
		for(int i=0;i<arraylist.size();i++){
			System.out.print(arraylist.get(i)+" ");
		}
		System.out.println();
	}
	 public static void main(String[] args) {
		ArrayList<String> arraylist=new ArrayList<String>();
		//对这个集合的增删改查
		//增
		arraylist.add("张1");
		arraylist.add("张2");
		arraylist.add("张3");
		arraylist.add("张4");
		arraylist.add("张5");
	
		print(arraylist);
		// 删除
		arraylist.remove(0);
		print(arraylist);
		//改
		arraylist.set(2, "测试");
		print(arraylist);
		//查
	    System.out.println(arraylist.get(3));
	}
}

LinkedList:

import java.util.LinkedList;
public class TestLinkedList {
	public static void print(LinkedList<String> linkedlist){
		System.out.println("输出的集合是:");
		for(int i=0;i<linkedlist.size();i++){
			System.out.print(linkedlist.get(i)+" ");
		}
		System.out.println();
	}
	public static void main(String[] args) {
		 LinkedList<String> linkedlist=new LinkedList<String>();
		 	linkedlist.add("张三");
	        linkedlist.add("李四");
	        linkedlist.add("王五");
	        linkedlist.add("李四");
	        linkedlist.add("赵六");
	        print(linkedlist);
	        System.out.println("-------------对数据进行操作---------------");
	        // 返回集合的长度
	        System.out.println(linkedlist.size());
	        //向集合索引为2位置中插入一个值
	        linkedlist.add(2, "测试");
	        print(linkedlist);
	        //从此列表中移除第一次出现的指定元素
	        linkedlist.remove("李四");
	        print(linkedlist);
	        //indexOf 寻找位置
	        System.out.println(linkedlist.indexOf("李四"));
	        //peekFirst 获取第一个元素
	        System.out.println(linkedlist.peekFirst());
	        //peekFirst 获取最后的元素
	        System.out.println(linkedlist.peekLast());
	}
}
3.集合的遍历

Iterator和foreach

lterator:

// 先创一个Student类
package com.java1234_8;

public class Student {
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Student() {
		super();
	}
}
// lterator 
import java.util.Iterator;
import java.util.LinkedList;
public class LteratorTest {
	public static void main(String[] args) {
		LinkedList<Student>  linkedlist=new LinkedList<Student>();
		linkedlist.add(new Student("张三",30));
		linkedlist.add(new Student("李四",20));
		linkedlist.add(new Student("王二",60));
		linkedlist.add(new Student("麻子",50));
	    // 	System.out.println(linkedlist);
		 /**
         * 用Iterator遍历集合
         */
		 Iterator<Student> it=linkedlist.iterator();  // 返回一个迭代器
		 //has.Next判断有没有值
	        while(it.hasNext()){
	        	// .next为取值
	            Student s=it.next();   // 返回迭代的下一个元素。
	            System.out.println("姓名:"+s.getName()+"年龄:"+s.getAge());
	        }
	}
}
//

HashSet:

Set集合是Collection接口的子接口,没有对Collection接口进行扩展,里面不允许存在重复的内容;

import java.util.HashSet;
import java.util.Iterator;
 
public class TestHashSet {
 
    public static void main(String[] args) {
        /**
         * 1,HashSet是无序
         * 2,不循序有重复的值
         */
        HashSet<String> hs=new HashSet<String>();
        hs.add("21221");
        hs.add("112");
        hs.add("312");
        hs.add("421");
        hs.add("312");
         
        /**
         * 用Iterator遍历集合
         */
        Iterator<String> it=hs.iterator();
        while(it.hasNext()){
            String s=it.next();
            System.out.println(s+" ");
        }
    }
}

HashMap集合:

是存放一对值的最大接口,即接口中的每一个元素都是一对,以key->value键值对的形式保存;

import java.util.HashMap;
import java.util.Iterator;
 
public class TestHashMap {
 
    public static void main(String[] args) {
        HashMap<String,Student> hashMap=new HashMap<String,Student>();
        hashMap.put("1号", new Student("张三",10));
        hashMap.put("2号", new Student("李四",20));
        hashMap.put("3号", new Student("王五",30));
         
        // 通过key,获取value
        Student s=hashMap.get("1号");
        System.out.println(s.getName()+":"+s.getAge());
         
        Iterator<String> it=hashMap.keySet().iterator(); // 获取key的集合,再获取迭代器
        while(it.hasNext()){
            String key=it.next();  // 获取key
            Student student=hashMap.get(key);  // 通过key获取value
            System.out.println("key="+key+" value=["+student.getName()+","+student.getAge()+"]");
        }
    }
}
九、Java多线程
1.Java多线程-多线程的引入

什么是多线程呢,我可以简单的理解成 一边吃饭,一边听音乐 这个是多线程;假如 吃完饭再听音乐,或者先听音乐再吃饭,这个是单线程。

程序里同时执行多个任务并且加以控制 这个是java多线程的含义。同时干多个事,能充分利用cpu 内存等硬件设备,提高程序运行效率。

public class Test01 {
 
    /**
     * 听音乐
     */
    private static void music(){
        for(int i=0;i<100;i++){
            System.out.println("听音乐");
        }
    }
     
    /**
     * 吃饭
     */
    private static void eat(){
        for(int i=0;i<100;i++){
            System.out.println("吃饭");
        }
    }
     
    public static void main(String[] args) {
        music();
        eat();
    }
}
//我们用上多线程,一般吃饭,一边听音乐, 
//Eat线程类:
public class Eat extends Thread{
 
    @Override
    public void run() {
        for(int i=0;i<100;i++){
            try {
                Thread.sleep(100);
                System.out.println("吃饭");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
     
}

//Music类:
public class Music extends Thread{
 
    @Override
    public void run() {
        for(int i=0;i<100;i++){
            try {
                Thread.sleep(100);
                System.out.println("听音乐");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
}
//测试
public class Test02 {
 
    public static void main(String[] args) {
        Music musicThread=new Music();
        Eat eatThread=new Eat();
        musicThread.start();
        eatThread.start();
    }
}
2.Java多线程-Java多线程实现

1,继承Thread类

2,实现Runnable接口

3,多线程实现数据共享

// 1,继承Thread类
public class Thread1 extends Thread{
 
    private int baoZi=1;
     
    private String threadName;
 
    public Thread1(String threadName) {
        super();
        this.threadName = threadName;
    }

    @Override
    public void run() {
        while(baoZi<=10){
            System.out.println(threadName+" 吃"+baoZi+"第个包子");
            baoZi++;
        }
    }
    
    public static void main(String[] args) {
        // 张三 李四一起吃包子 每人吃10个
        Thread1 t1=new Thread1("张三线程");
        Thread1 t2=new Thread1("李四线程");
        t1.start();
        t2.start();
    }  
}
//2,实现Runnable接口
public class Thread2 implements Runnable{
 
    private int baoZi=1;
     
    private String threadName;
 
    public Thread2(String threadName) {
        super();
        this.threadName = threadName;
    }
 
    @Override
    public void run() {
        while(baoZi<=10){
            System.out.println(threadName+" 吃"+baoZi+"第个包子");
            baoZi++;
        }
    }
     
    public static void main(String[] args) {
        // 张三 李四一起吃包子 每人吃10个
        Thread2 t1=new Thread2("张三线程");
        Thread2 t2=new Thread2("李四线程");
        Thread t11=new Thread(t1);
        Thread t12=new Thread(t2);
        t11.start();
        t12.start();
    }
 
}
//3,多线程实现数据共享
public class Thread3 implements Runnable{
 
    private int baoZi=1;
     
    private String threadName;
 
    public Thread3(String threadName) {
        super();
        this.threadName = threadName;
    }
 
    @Override
    public synchronized void run() {
        while(baoZi<=10){
            System.out.println(threadName+" 吃"+baoZi+"第个包子");
            baoZi++;
        }
    }
     
    public static void main(String[] args) {
        Thread3 t1=new Thread3("超级张三线程");
        Thread t11=new Thread(t1);
        Thread t12=new Thread(t1);
        Thread t13=new Thread(t1);
        t11.start();
        t12.start();
        t13.start();
    }
 
}
3.Java多线程-线程的状态

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gUQtXx9I-1657878648851)(D:\java1234\java1234笔记\java1234笔记截图\image-20220714212750489.png)]

1,创建状态

在程序中用构造方法创建了一个线程对象后,新的线程对象便处于新建状态,此时,它已经有了相应的

内存空间和其他资源,但还处于不可运行状态。新建一个线程对象可采用Thread 类的构造方法来实现,例

如,“Thread thread=new Thread();”。

2,就绪状态

新建线程对象后,调用该线程的start()方法就可以启动线程。当线程启动时,线程进入就绪状态。此时,

线程将进入线程队列排队,等待CPU 服务,这表明它已经具备了运行条件。

3,运行状态

当就绪状态的线程被调用并获得处理器资源时,线程就进入了运行状态。此时,自动调用该线程对象

的run()方法。run()方法定义了该线程的操作和功能。

4,堵塞状态

一个正在执行的线程在某些特殊情况下,如被人为挂起或需要执行耗时的输入/输出操作时,将让出

CPU 并暂时中止自己的执行,进入堵塞状态。堵塞时,线程不能进入排队队列,只有当引起堵塞的原因被

消除后,线程才可以转入就绪状态。

5,死亡状态

线程调用stop()方法时或run()方法执行结束后,即处于死亡状态。处于死亡状态的线程不具有继续运

行的能力。

4.Java多线程-线程常用方法

1,getName(); 返回该线程的名称。

2,currentThread();返回对当前正在执行的线程对象的引用。

3,isAlive();测试线程是否处于活动状态。

4,sleep();线程休眠。

5,setPriority(int newPriority);更改线程的优先级。

6,yield();暂停当前正在执行的线程对象,并执行其他线程。

public class Demo1 implements Runnable{
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10;i++){
            // 获取当前线程
            Thread t=Thread.currentThread();
            System.out.println(t.getName()+":"+i); // 返回线程的名称
        }
    }
     
    public static void main(String[] args) {
        Demo1 demo1=new Demo1();
        new Thread(demo1).start();
        new Thread(demo1).start();
        new Thread(demo1,"线程3").start();
    }
 
}
//
public class Demo2 implements Runnable{
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10;i++){
            // 获取当前线程
            Thread t=Thread.currentThread();
            System.out.println(t.getName()+":"+i); // 返回线程的名称
        }
    }
     
    public static void main(String[] args) {
        Demo2 demo2=new Demo2();
        Thread t1=new Thread(demo2);
        System.out.println("t1是否活动:"+t1.isAlive());
        t1.start();
        System.out.println("t1是否活动:"+t1.isAlive());
    }
}
//
public class Demo3 implements Runnable{
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10;i++){
            try {
                Thread.sleep(1000);
                // 获取当前线程
                Thread t=Thread.currentThread();
                System.out.println(t.getName()+":"+i); // 返回线程的名称
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
     
    public static void main(String[] args) {
        Demo3 demo1=new Demo3();
        new Thread(demo1).start();
    }
 
}
//
public class Demo4 implements Runnable{
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10;i++){
            try {
                Thread.sleep(1000);
                // 获取当前线程
                Thread t=Thread.currentThread();
                System.out.println(t.getName()+":"+i); // 返回线程的名称
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
     
    public static void main(String[] args) {
        Demo4 demo4=new Demo4();
        Thread t1=new Thread(demo4,"线程A");
        Thread t2=new Thread(demo4,"线程B");
        Thread t3=new Thread(demo4,"线程C");
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setPriority(Thread.MIN_PRIORITY);
        t3.setPriority(Thread.NORM_PRIORITY);
        t3.start();
        t1.start();
        t2.start();
    }
 
}
//
public class Demo5 implements Runnable{
 
    @SuppressWarnings("static-access")
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10;i++){
            try {
                Thread.sleep(100);
                // 获取当前线程
                Thread t=Thread.currentThread();
                System.out.println(t.getName()+":"+i); // 返回线程的名称
                if(i==5){
                    System.out.println("线程礼让:");
                    Thread.currentThread().yield();
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
     
    public static void main(String[] args) {
        Demo5 demo1=new Demo5();
        new Thread(demo1,"线程A").start();
        new Thread(demo1,"线程B").start();
    }
 
}
5.Java多线程-线程同步
public class Thread1 implements Runnable{
 
    private int baoZi=1;
     
    private String threadName;
 
    public Thread1(String threadName) {
        super();
        this.threadName = threadName;
    }
 
    @Override
    public void run() {
        while(baoZi<=10){
            System.out.println(threadName+" 吃第"+baoZi+"个包子");
            baoZi++;
        }
    }
     
    public static void main(String[] args) {
        Thread1 t1=new Thread1("超级张三线程");
 
        Thread t11=new Thread(t1);
        Thread t12=new Thread(t1);
        Thread t13=new Thread(t1);
         
        t11.start();
        t12.start();
        t13.start();
    }
 
}
// 我们发现 会有多个线程同时进入方法吃包子的情况发生,这时候,就引入了线程同步。可以给方法加同步,同一时刻,只允许一个线程进入方法;

// 关键字 synchronized
public class Thread3 implements Runnable{
 
    private int baoZi=1;
     
    private String threadName;
 
    public Thread3(String threadName) {
        super();
        this.threadName = threadName;
    }
 
    @Override
    public synchronized void run() {
        while(baoZi<=10){
            System.out.println(threadName+" 吃第"+baoZi+"个包子");
            baoZi++;
        }
    }
     
    public static void main(String[] args) {
        Thread3 t1=new Thread3("超级张三线程");
 
        Thread t11=new Thread(t1);
        Thread t12=new Thread(t1);
        Thread t13=new Thread(t1);
         
        t11.start();
        t12.start();
        t13.start();
    }
 
}
//
public class Thread4 implements Runnable{
 
    private int baoZi=1;
     
    private String threadName;
 
    public Thread4(String threadName) {
        super();
        this.threadName = threadName;
    }
 
    @Override
    public void run() {
        /**
         * 同步块
         */
        synchronized (this) {
            while(baoZi<=10){
                System.out.println(threadName+" 吃第"+baoZi+"个包子");
                baoZi++;
            }
        }
    }
     
    public static void main(String[] args) {
        Thread4 t1=new Thread4("超级张三线程");
 
        Thread t11=new Thread(t1);
        Thread t12=new Thread(t1);
        Thread t13=new Thread(t1);
         
        t11.start();
        t12.start();
        t13.start();
    }
 
}
十、JavaIO流
1.IO 流简介**

定义:流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QMB4F0mj-1657878648852)(D:\java1234\java1234笔记\java1234笔记截图\image-20220714221038141.png)]

IO 流的分类

根据处理数据类型的不同分为:字符流和字节流

根据数据流向不同分为:输入流和输出流

2.文件操作File 类

1,public boolean mkdir() 创建此抽象路径名指定的目录。

2,public boolean createNewFile() 创建一个文件

3,public boolean delete() 删除此抽象路径名表示的文件或目录。如果此路径名表示一个目录,则该目录

必须为空才能删除。

4,public boolean exists() 测试此抽象路径名表示的文件或目录是否存在。

5,public File[] listFiles() 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文

件。

6,public boolean isDirectory() 测试此抽象路径名表示的文件是否是一个目录。

//创建文件目录和文件 
import java.io.File;
import java.io.IOException;
 
public class Demo1 {
 
    public static void main(String[] args) throws IOException {
        File file=new File("c://java创建的目录");
        boolean b=file.mkdir();  // 创建虚拟目录
        if(b){
            System.out.println("目录创建成功!");
            file=new File("c://java创建的目录//java创建的文件.txt");
            boolean b2=file.createNewFile();  // 创建文件
            if(b2){
                System.out.println("文件创建成功!");
            }else{
                System.out.println("文件创建失败!");
            }
        }else{
            System.out.println("目录创建失败!");
        }
    }
}
// 删除文件和文件目录
import java.io.File;
import java.io.IOException;
 
public class Demo2 {
 
    public static void main(String[] args) throws IOException {
        File file=new File("c://java创建的目录//java创建的文件.txt");
        if(file.exists()){  // 假如文件存在
            boolean b=file.delete();  // 删除文件
            if(b){
                System.out.println("删除文件成功!");
            }else{
                System.out.println("删除文件失败!");
            }
        }
        file=new File("c://java创建的目录");
        if(file.exists()){
            boolean b=file.delete();  // 删除目录
            if(b){
                System.out.println("删除目录成功!");
            }else{
                System.out.println("删除目录失败!");
            }
        }
    }
}
//遍历目录
import java.io.File;
 
public class Demo3 {
 
    public static void main(String[] args) {
        File file=new File("C://apache-cxf-3.1.5");
        File files[]=file.listFiles();  // 遍历目录
        for(int i=0;i<files.length;i++){
            System.out.println(files[i]);
        }
    }
}
//递归遍历所有文件
import java.io.File;
 
public class Demo4 {
 
    /**
     * 打印文件
     * @param file
     */
    public static void listFile(File file){
        if(file!=null){
            if(file.isDirectory()){  // 是目录
                System.out.println(file);  // 打印下目录
                File f[]=file.listFiles();  // 遍历目录
                if(f!=null){
                    for(int i=0;i<f.length;i++){
                        listFile(f[i]);  // 递归调用
                    }
                }
            }else{   // 是文件
                System.out.println(file);  // 是文件,直接打印文件的路径
            }
        }
    }
     
    public static void main(String[] args) {
        File file=new File("C://apache-tomcat-7.0.63");
        listFile(file);
    }
}
3.Java IO流-InputStream和OutputStream

InputStream是输入流 OutputStream是输出流;

InputStream输入流可以把文件从硬盘读取到内存;

OutputStream输出流可以把文件从内存写入到硬盘;

我们实际使用的都是InputStream和OutputStream的子类;

比如文件操作方面用的是FileInputStream和FileOutputStream;

准备工作,我们在C盘建一个txt文件 测试文件.txt ,随便加点内容:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AsP8GYTY-1657878648853)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220714222708236.png)]

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
 
public class Demo1 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        InputStream inputStream=new FileInputStream(file);  // 实例化FileInputStream
        byte b[]=new byte[1024];
        int len=inputStream.read(b);
        inputStream.close(); // 关闭输入流
        System.out.println("读取的内容是:"+new String(b,0,len));
    }
}

//上面那个是定义了固定字节数组 一批读取的,我们现在改进下,获取文件长度,然后定义指定字节数组的长度;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
 
public class Demo2 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        InputStream inputStream=new FileInputStream(file);  // 实例化FileInputStream
        int fileLength=(int)file.length();
        byte b[]=new byte[fileLength];
        inputStream.read(b);
        inputStream.close(); // 关闭输入流
        System.out.println("读取的内容是:"+new String(b));
    }
}
//我们再来一种方式 一个字节一个字节读取;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
 
public class Demo3 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        InputStream inputStream=new FileInputStream(file);  // 实例化FileInputStream
        int fileLength=(int)file.length();
        byte b[]=new byte[fileLength];
        int temp=0;
        int len=0;
        while((temp=inputStream.read())!=-1){
            // 一个字节一个字节读取,放到b字节数组里
            b[len++]=(byte)temp;
        }
        inputStream.close(); // 关闭输入流
        System.out.println("读取的内容是:"+new String(b));
    }
}

//输出流;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
public class Demo4 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        OutputStream out=new FileOutputStream(file);
        String str="你好,我好,大家好,Java好";
        byte b[]=str.getBytes();
        out.write(b); //  将b字节数组写入到输出流
        out.close();  // 关闭输出流
    }
}
//我们把指定文件写入到文件;
//上面那种是直接覆盖的,我们再来一个追加的;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
public class Demo5 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        OutputStream out=new FileOutputStream(file,true);
        String str="你好,我好,大家好,Java好";
        byte b[]=str.getBytes();
        out.write(b); //  将b字节数组写入到输出流
        out.close();  // 关闭输出流
    }
}
4.Java IO流-BufferedInputStream和BufferedOutputStream

带缓冲的输入和输出流;

这里缓冲的概念,就是在A,B之间建立内存缓冲区,读取得快,就先放缓冲区,然后再从缓冲区写入指定目标,和没有缓冲比,效率快很多。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
 
public class Demo6 {
 
    /**
     * 缓冲
     * @throws Exception
     */
    public static void bufferStream()throws Exception{
        // 定义了一个带缓冲的字节输入流
        BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("C://《一头扎进J2SE》V2.0视频笔录2.doc"));
        // 定义了一个带缓冲的字节输出流
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("C://复制的《一头扎进J2SE》V2.0视频笔录2.doc"));
        int b=0;
        long startTime=System.currentTimeMillis(); // 开始时间
        while((b=bufferedInputStream.read())!=-1){
            bufferedOutputStream.write(b);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
        long endTime=System.currentTimeMillis();  // 结束时间
        System.out.println("缓冲花费的时间是:"+(endTime-startTime));
    }
     
    /**
     * 非缓冲
     * @throws Exception
     */
    public static void stream() throws Exception{
        InputStream inputStream=new FileInputStream("C://《一头扎进J2SE》V2.0视频笔录.doc");  // 定义一个输入流
        OutputStream outputStream=new FileOutputStream("C://复制的《一头扎进J2SE》V2.0视频笔录.doc");
        int b=0;
        long startTime=System.currentTimeMillis(); // 开始时间
        while((b=inputStream.read())!=-1){
            outputStream.write(b);
        }
        inputStream.close();
        outputStream.close();
        long endTime=System.currentTimeMillis();  // 结束时间
        System.out.println("非缓冲花费的时间是:"+(endTime-startTime));
    }
     
    public static void main(String[] args)throws Exception {
        stream();
        bufferStream();
    }
}
//把文件从A地址复制到B地址,运行输出:

//非缓冲花费的时间是:2368   缓冲花费的时间是:31

//我们明显发现 带缓冲的效率高;
5.Java IO流-Reader和Writer

主要用于文本的读取和写入,一般使用的实现类是FileReader和FileWriter;


import java.io.File;
import java.io.FileReader;
import java.io.Reader;
 
public class Demo1 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        Reader reader=new FileReader(file);
        char c[]=new char[1024]; // 字符数组
        int len=reader.read(c);
        reader.close();  // 关闭输入流
        System.out.println("读取的内容是:"+new String(c,0,len));
    }
}
// 直接读取;


import java.io.File;
import java.io.FileReader;
import java.io.Reader;
 
public class Demo2 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        Reader reader=new FileReader(file);
        char c[]=new char[1024]; // 字符数组
        int temp=0;
        int len=0;
        while((temp=reader.read())!=-1){
            c[len++]=(char)temp;
        }
        reader.close();  // 关闭输入流
        System.out.println("读取的内容是:"+new String(c,0,len));
    }
}
// 一个一个字符读取;


import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
 
public class Demo3 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        Writer out=new FileWriter(file);
        String str="我爱中华";
        out.write(str);  // 将字符串写入输出流
        out.close();  // 关闭输出流
    }
}
// 写入文件;


import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
 
public class Demo4 {
 
    public static void main(String[] args) throws Exception {
        File file=new File("C://测试文件.txt");
        Writer out=new FileWriter(file,true);
        String str="我爱中华2";
        out.write(str);  // 将字符串写入输出流
        out.close();  // 关闭输出流
    }
}
//追加写入;


解决eclipse控制台信息显示不全问题

解决eclipse控制台信息显示不全问题

eclipes控制台有默认的显示行数或者大小;

我们可以设置下,来增大显示行数;

菜单->windows->preferences

搜索console

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k0zFmrRG-1657878648859)(D:\java1234\java1234笔记\java1234笔记截图\image-20220714224611125.png)]

十一、java debug断点调试的重要性

java debug断点调试的重要性

以掌握好debug断点调试,我们无需搞输出语句 直接打断点,程序执行到断点处停止,我们可以直接观察变量的值,以及表达式的值,我们甚至可以

动态修改变量的值来调试,非常方便,然后我们可以控制调试的执行,主要有F6 执行下一步,F8执行完成或者执行到下一个断点,F5进入方法内部;

1.eclipse debug使用基本操作

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BVVHhEBf-1657878648860)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220714225400501.png)]

2.eclipse debug常见调试 F6 单步 F8完成 F5进入方法

eclipse 里debug调试主要三个快捷方式

F6 单步执行 执行到下一行代码

F8是执行完 假如后面还有断点 执行到下一个断点处

F5是进入方法里执行

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MPAGdief-1657878648861)(D:\java1234\java1234笔记\java1234笔记截图\image-20220714225516462.png)]

3.eclipse debug ctrl+shift+i查看表示式值

eclipse debug ctrl+shift+i查看表示式值

在eclipse里debug断点调试的时候,当我们需要查看某个表达式的时候,可以用ctrl+shift+i快捷方式;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nmdW5r4X-1657878648862)(D:\java1234\java1234笔记\java1234笔记截图\image-20220714225642044.png)]

4.eclipse debug 运行时动态修改变量值

这里讲一个高级点的debug功能,就是可以运行时候,动态修改变量的值。在企业级开发中,往往搞点测试数据麻烦,

所以直接debug的时候随便改数据,来进行各种测试,比较方便;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

public class Demo4 {

public static void main(String[] args) throws Exception {
    File file=new File("C://测试文件.txt");
    Writer out=new FileWriter(file,true);
    String str="我爱中华2";
    out.write(str);  // 将字符串写入输出流
    out.close();  // 关闭输出流
}

}
//追加写入;


#### **解决eclipse控制台信息显示不全问题**

解决eclipse控制台信息显示不全问题

eclipes控制台有默认的显示行数或者大小;

我们可以设置下,来增大显示行数;

菜单->windows->preferences

搜索console

[外链图片转存中...(img-k0zFmrRG-1657878648859)]

#### 十一、**java debug断点调试的重要性**

java debug断点调试的重要性

以掌握好debug断点调试,我们无需搞输出语句 直接打断点,程序执行到断点处停止,我们可以直接观察变量的值,以及表达式的值,我们甚至可以

动态修改变量的值来调试,非常方便,然后我们可以控制调试的执行,主要有F6 执行下一步,F8执行完成或者执行到下一个断点,F5进入方法内部;

##### 1.**eclipse debug使用基本操作**

[外链图片转存中...(img-BVVHhEBf-1657878648860)]

##### 2.**eclipse debug常见调试 F6 单步 F8完成 F5进入方法**

eclipse 里debug调试主要三个快捷方式 

F6 单步执行 执行到下一行代码

F8是执行完 假如后面还有断点 执行到下一个断点处

F5是进入方法里执行

[外链图片转存中...(img-MPAGdief-1657878648861)]

##### 3.**eclipse debug ctrl+shift+i查看表示式值**

eclipse debug ctrl+shift+i查看表示式值

在eclipse里debug断点调试的时候,当我们需要查看某个表达式的时候,可以用ctrl+shift+i快捷方式;

[外链图片转存中...(img-nmdW5r4X-1657878648862)]

##### 4.**eclipse debug 运行时动态修改变量值**

这里讲一个高级点的debug功能,就是可以运行时候,动态修改变量的值。在企业级开发中,往往搞点测试数据麻烦,

所以直接debug的时候随便改数据,来进行各种测试,比较方便;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q30gmBb3-1657878648863)(D:\java1234\java1234笔记\java1234笔记截图\image-20220714225754486.png)]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沁颖呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值