//操作比较大的数的时候,注意溢出问题 //JDK7新特性,数字之间可以用下划线分割 int money = 10_0000_0000; int years = 20; int tota1 = money*years;//-1474836480,计算的时候溢出了 int total2 = money*(long)years;//20000000000
public class text { public static void main(String[] args) { try { new text().test(1,0); } catch (ArithmeticException e) { e.printStackTrace(); } } public void test(int a,int b) throws ArithmeticException{ if(b==0){ throw new ArithmeticException();//主动抛出异常,一般在方法中使用 } } }
public class Test { //jak5之前,手动装箱和手动拆箱 int n1 = 100; Integer integer = new Integer(n1); Integer integer1 = Integer.valueOf(n1); int i = integer.intValue(); //jdk5后,就可以自动装箱和自动拆箱 int n2 = 200; //自动装箱 int->Integer Integer integer2 = n2; //自动拆箱 Integer->int int n3 = integer2; }
public class StringTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); for(int i=0;i<line.length();i++){ System.out.println(line.charAt(i)); } } }
//public Date();分配一个Date对象,并初始化,以便它代表它被分配的时间,精确的毫秒 Date d1 = new Date(); System.out.println(d1); //Sun Dec 26 23:28:48 CST 2021
//public Date(long date); 分配一个Date对象,并将其初始化为便是从标准基准时间起指定的毫秒数 long date = 1000*60*60; Date d2 = new Date(date); System.out.println(d2); //Thu Jan 01 09:00:00 CST 1970
常用方法
1 2 3 4 5 6 7 8
Date d = new Date(); //public long getTime();获取的是日期对象从1970年1月1日 00:00:00到现在的毫秒值。 System.out.println(d.getTime());
//public void setTime(long time);设置时间,给的时毫秒值。 long time = System.currentTimeMillis();//当前时间 d.setTime(time); System.out.println(d);
//格式化,从Date到String //public final String format(Date date);将日期格式化成日期/时间字符串 Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(); String s = sdf.format(d); System.out.println(s);//21-12-27 上午12:53
//Calendar提供了一个类方法getInstance用于获取Calendar对象,其日历字段已实验当前日期和时间初始化 Calendar c = Calendar.getInstance(); //public int get(int field);返回给定日历字段的值 int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int date = c.get(Calendar.DATE); System.out.println(year + "年" + month + "月" + date + "日");
//public abstract void add(int field,int amount);根据日历的规则,将指定的时间量添加或减去给定的日历字段 //10年前的5天后 c.add(Calendar.YEAR,-10); c.add(Calendar.DATE,5); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int date = c.get(Calendar.DATE); System.out.println(year + "年" + month + "月" + date + "日");
//public final void set(int year,int month,int date);设置当前日历的年月日 Calendar c1 = Calendar.getInstance(); c1.set(2016,11,13); int year1 = c1.get(Calendar.YEAR); int month1 = c1.get(Calendar.MONTH)+1; int date1 = c1.get(Calendar.DATE); System.out.println(year1 + "年" + month1 + "月" + date1 + "日");
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Scanner sc = new Scanner(System.in); System.out.println("请输入年份:"); int year = sc.nextInt();
Calendar c = Calendar.getInstance(); c.set(year,2,1); c.add(Calendar.DATE,-1); int date = c.get(Calendar.DATE); System.out.println(year + "年的2月份有" + date + "天"); //请输入年份: //2016 //2016年的2月份有29天
集合
集合类的特点:提供一种存储空间可变的存储模型,存储的数据容量可以发生改变
ArrayList
ArrayList:
可调整大小的数组实现
:是一种特殊的数据类型,泛型
构造和添加方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class ArrayListDemo01 { public static void main(String[] args) { //public ArrayList();创建一个空的集合对象 ArrayList<String> array= new ArrayList<String>();
int[] arr = {1,2,3,4}; for(int i : arr){ System.out.println(i); }
List<String> list = new ArrayList<String>(); list.add("hello"); list.add("hello2"); list.add("hello3");
for(String s : list){ System.out.println(s); }
List集合子类
List集合常用子类:ArrayList、LinkedList
ArrayList:底层数据结构是数组,查询快,增删慢
LinkedList:底层数据结构是链表,查询慢,增删快
LinkedList集合的特有功能
public void addFirst(E e); 在该列表开头插入指定的元素
public void addLast(E e); 将指定的元素追加到此列表的末尾
public E getFirst(); 返回此列表中的第一个元素
public E getLast(); 返回此列表中的最后一个元素
public E removeFirst(); 从此列表中欧给删除并返回第一个元素
public E removeLast(); 从此列表中欧给删除并返回最后一个元素
Set
set集合特点
不包含重复元素的集合
没有带索引的方法,所以不能使用普通for循环遍历
1 2 3 4 5 6 7
Set<String> set = new HashSet<String>(); set.add("hello1"); set.add("hello2"); set.add("hello3"); for(String s : set){ System.out.println(s); }
哈希值
哈希值:是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值
Object类中有一个方法可以获取对象的哈希值
Public int hashCode(); 返回对象的哈希码值
对象的哈希值特点
同一个对象多次调用hashCode()方法返回的哈希值是相同的
默认情况下,不同对象的哈希值是不同的,而重写hasCode()方法,可以使其相同
HashSet
集合特点
底层数据结构使哈希表
对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致
没有带索引的方法,所以不能使用普通for循环遍历
由于是Set集合,所以不包含重复元素
LinkedHashSet
LinkedHashSet集合概述和特点
哈希表和链表实现的Set接口,具有可预测的迭代次序
由链表保证元素有序,也就是说元素的存储和取出顺序一致
由哈希表保证元素唯一,也就是说没有重复的元素
TreeSet
TreeSet集合特点
元素有序,这里的顺序不是指存储和取出的顺序,而是按照一定的规则进行排序,具体排序方法取决于构造方法
TreeSet(); 根据其元素的自然排序进行排序
TreeSet(Comparator comparator); 根据指定的比较器进行排序
没有带索引的方法,所以不能使用普通的for循环遍历
由于是Set集合,所以不包含重复元素的集合
Comparable
用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的
自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(T o)方法
重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写
1 2 3 4 5
public int compareTo(Student s){ int num = this.age - s.age; int num2 = num == 0?this.name.compareTo(s.name):num; return num; }
Comparator
1 2 3 4 5 6 7
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){ public int compare(Student s1,Student s2){ int num = s1.getAge() - s2.getAge(); int num2 = num == 0?s1.getName().compareTo(s2.getName()):num; return num2; } })
泛型
泛型:是JDK5中引入的特性,它提供了编译时类型安全检测机制,该极致允许在编译时检测到非法的类型
它的本质时参数化类型,也就是说所操作的数据类型被指定为一个参数
泛型定义格式:
<类型>:指定一种类型的格式。这里的类型可以看成是形参
<类型1,类型2…>:指定多种类型的格式,多种类型之间用逗号隔开。这里的类型可以看成事形参
将来具体调用时给定的类型可以看成事实参,并且实参的类型只能是引用数据类型
泛型的好处:
把运行时期的问题提前到了编译期间
避免了强制类型转换
泛型类
泛型类的定义格式:
格式:修饰符 class 类名 <类型>{}
范例:public class Generic{}
此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
1 2 3 4 5 6 7 8 9 10 11
public class Generic<T> { private T t;
public T getT() { return t; }
public void setT(T t) { this.t = t; } }
1 2 3 4 5 6 7 8 9 10 11 12
public class GenericDemo { public static void main(String[] args) { Generic<String> g1 = new Generic<>(); g1.setT("xingchuwu"); System.out.println(g1.getT());
Generic<Integer> g2 = new Generic<>(); g2.setT(100); System.out.println(g2.getT()); } }
泛型方法
泛型方法的定义格式:
格式:修饰符 <类型> 返回值类型 方法名(类型 变量名){}
范例:public void show(T t){}
1 2 3 4 5
public class Generic{ public <T> void show(T t){ System.out.println(t); } }
1 2 3 4 5 6 7
public class GenericDemo { public static void main(String[] args) { Generic g = new Generic(); g.show("xingchuwu"); g.show(100); } }
泛型接口
泛型接口的定义格式:
格式:修饰符 interface 接口名<类型>{}
范例:public interface Generic{}
1 2 3
public interface Generic1<T> { void show(T t); }
1 2 3 4 5 6
public class GenericImpl<T> implements Generic1<T> { @Override public void show(T t) { System.out.println(t); } }
1 2 3 4 5 6 7 8 9
public class GenericDemo1 { public static void main(String[] args) { GenericImpl<String> g = new GenericImpl<>(); g.show("xingchuwu");
GenericImpl<Integer> g1 = new GenericImpl<>(); g1.show(100); } }
List<?> list1 = new ArrayList<Object>(); List<?> list2 = new ArrayList<Number>(); List<?> list3 = new ArrayList<Integer>(); List<? extends Number> list4 = new ArrayList<Number>(); List<? extends Number> list5 = new ArrayList<Integer>();
List<? super Number> list6 = new ArrayList<Object>(); List<? super Number> list7 = new ArrayList<Number>();
可变参数
可变参数又称参数个数可变,用作方法的形参出现,那么方法的参数个数就是可变的了
格式:修饰符 返回值类型 方法名(数据类型…变量名){}
范例:public static int sum(int…a){}
注意事项:
这里的变量其实是一个数组
如果一个方法有多个参数,包含可变参数,可变参数要放在最后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class ArgsDemo { public static void main(String[] args) { System.out.println(sum(10,20)); System.out.println(sum(10,20,30)); System.out.println(sum(10,20,30,40)); }
public static int sum (int...a){ int sum = 0; for(int i : a){ sum += i; } return sum; } }
可变参数的使用
Arrays工具类中有一个静态方法:
public static List asList(T…a); 返回由指定数组支持的固定大小的列表
返回的集合不能做增删操作,可以做修改操作
List接口中有一个静态方法:
public static List of(E…elements); 返回包含任意数量元素的不可变列表
返回的集合不能做增删改操作
Set接口中有一个静态方法:
public static Set of(E…elements); 返回一个包含任意数量元素的不可变集合
返回的集合不能做增删操作,没有修改的方法
Map
Map集合概述:
Interface Map<K,V> K:健的类型;V:值的类型
将健映射到值的对象;不能包含重复的健;每个健可以映射到最多一个值
举例:学生的学号和姓名
创建Map集合的对象:
多态的方式
具体的实现类HashMap
1 2 3 4 5 6 7 8 9 10 11
public class MapDemo1 { public static void main(String[] args) { Map<String,String> map = new HashMap<>();
public class MapDemo3 { public static void main(String[] args) { ArrayList<HashMap> arrayList = new ArrayList<>(); HashMap<String,String> hm1 = new HashMap<>();
public class CollectionsDemo2 { public static void main(String[] args) { ArrayList<Student> arrayList = new ArrayList<>();
Student s1 = new Student("xingchuwu",20); Student s2 = new Student("qianxiyunu",19); Student s3 = new Student("xxx",35); Student s4 = new Student("aaa",20);
Collections.sort(arrayList, new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int num = s1.getAge() -s2.getAge(); int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; return num2; } });
public class CollectionsDemo3 { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<>();
String[] colors = {"♦","♠","♥","♣"}; String[] numbers = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; for(String color : colors){ for(String number : numbers) arrayList.add(color+number); } arrayList.add("大王"); arrayList.add("小王");
Collections.shuffle(arrayList);
ArrayList<String> dzArray = new ArrayList<>(); ArrayList<String> nmArray1 = new ArrayList<>(); ArrayList<String> nmArray2 = new ArrayList<>(); ArrayList<String> dpArray = new ArrayList<>();
for(int i=0; i<arrayList.size();i++){ String poker = arrayList.get(i);
public class CollectionsDemo4 { public static void main(String[] args) {
HashMap<Integer,String> hm = new HashMap<>();
String[] colors = {"♦","♠","♥","♣"}; String[] numbers = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; hm.put(0,"大王"); hm.put(1,"小王"); int num = 2; for(String number : numbers){ for(String color : colors){ hm.put(num,color+number); num++; } }
Set<Integer> keySet = hm.keySet(); for(Integer key : keySet){ String value = hm.get(key); StringBuilder sb = new StringBuilder(); sb.append(key).append(":").append(value); System.out.println(sb);
} ArrayList<Integer> arrayList = new ArrayList<>(); for(int i=0;i<52;i++) arrayList.add(i); Collections.shuffle(arrayList);
TreeSet<Integer> dzArray = new TreeSet<>(); TreeSet<Integer> nmArray1 = new TreeSet<>(); TreeSet<Integer> nmArray2 = new TreeSet<>(); TreeSet<Integer> dpArray = new TreeSet<>();
for(int i=0; i<arrayList.size();i++){ Integer poker = arrayList.get(i);
long start = System.currentTimeMillis(); for(int i = 0; i < 10000; i++){ System.out.println(i); } long end = System.currentTimeMillis(); System.out.println("共耗时:" + (end - start) + "毫秒");
Object
Object是类层次结构的根,每个类都可以将Object作为超类,所有类都直接或间接的继承自该类
构造方法:public Object();
常用方法
public String toString();//返回对象的字符串表示形式,建议所有子类重写此方法,自动生成即可
public boolean equals(Object obj);//比较对象是否相等。默认比较地址,重写可以比较内容,自动生成
Arrays
Arrays类包含用于操作数组的各种方法
常用方法
public static String toString(int[] a);返回指定数组的内容的字符串表示形式
public class FileDemo1 { public static void main(String[] args) { File f1 = new File("E:\\javadProgram\\javaIOTest\\java.txt"); System.out.println(f1);
File f2 = new File("E:\\javadProgram\\javaIOTest","java.txt"); System.out.println(f2);
File f3 = new File("E:\\javadProgram\\javaIOTest"); File f4 = new File(f3,"java.txt"); System.out.println(f4); } }
创建方法
public boolean createNewFile(); 当具有该名称的文件不存在时,创建一个由该抽象路径名命名的新空文件
public boolean mkdir(); 创建由此抽象路径名命名的目录
public boolean mkdirs(); 创建由此抽象路径名命名的目录,包括任何必须但不存在的父目录
1 2 3 4 5 6 7 8 9 10 11 12 13
public class FileDemo2 { public static void main(String[] args) throws IOException { File f1 = new File("E:\\javadProgram\\javaIOTest\\java.txt"); System.out.println(f1.createNewFile());
File f2 = new File("E:\\javadProgram\\javaIOTest\\javaSE"); System.out.println(f2.mkdir());
File f3 = new File("E:\\javadProgram\\javaIOTest\\javaWeb\\html"); System.out.println(f3.mkdirs()); } }
判断和获取功能
public boolean isDirectory(); 测试此抽象路径名表示的File是否为目录
public boolean isFile(); 测试此抽象路径名表示的File是否为文件
public boolean exists(); 测试此抽象路径名表示的File是否为存在
public String getAbsolutePath(); 返回此抽象路径名的绝对路径名字符串
public String getPath(); 将此抽象路径名转换为路径名字符串
public String getName(); 返回此抽象路径名表示的文件或目录的名称
public String[] list(); 返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
public File[] listFiles(); 返回此抽象路径名表示的目录中的文件和目录的File对象数组
public class FileDemo4 { public static void main(String[] args) { File f = new File("E:\\javadProgram\\javaIOTest"); if(f.exists()) getAllFilePath(f); } public static void getAllFilePath(File f){ File[] fileArray = f.listFiles(); if(fileArray != null){ for(File file : fileArray){ if(file.isDirectory()){ // System.out.print(file.getPath()); // System.out.println(":"); getAllFilePath(file); }else if(file.isFile()){ System.out.println(file.getAbsoluteFile()); } } } } }
字节流
字节流抽象基类:
InputStream:这个抽象类是表示字节输入流的所有类的超类
OutputStream:这个抽象类是表示字节输出流的所有类的超类
子类名特点:子类名称都是以其父类名作为子类名的后缀
FileOutputStream
FileOutputStream:文件输出流用于将数据写入File
FileOutputStream(String name):创建文件输出流以指定的名称写入文件
使用字节输出流写数据的步骤:
创建字节输出流对象(调用系统功能创建了文件,创建字节输出流对象,让字节输出流对象指向文件)
调用字节输出流对象的写数据方法
释放资源
1 2 3 4 5 6 7 8 9
public class FileOutputStreamDemo1 { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("E:\\javadProgram\\javaStudy\\src\\com\\chang\\base\\myIO\\ByteStreamDemo\\fos.txt");
public class FileOutputStreamDemo2 { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("E:\\javadProgram\\javaStudy\\src\\com\\chang\\base\\myIO\\ByteStreamDemo\\fos.txt");
public class FileInputStreamDemo1 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("fos.txt");
int by; while((by = fis.read()) != -1){ System.out.print((char)by); }
fis.close(); } }
读字节数组数据
1 2 3 4 5 6 7 8 9 10 11 12
public class FileInputStreamDemo3 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("fos.txt");
byte[] bys = new byte[1024]; //1024及其倍数 int len; while((len = fis.read(bys)) != -1){ System.out.println(new String(bys,0,len)); } fis.close(); } }
案例
字节流复制文本文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class FileInputStreamDemo2 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("fos.txt"); FileOutputStream fos = new FileOutputStream("E:\\javadProgram\\javaIOTest\\java.txt");
int by; while((by = fis.read()) != -1){ fos.write(by); }
fis.close(); fos.close();
} }
复制图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class FileInputStreamDemo4 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("E:\\UpupooWallpaper\\1800011075\\previewFix.jpg"); FileOutputStream fos = new FileOutputStream("E:\\javadProgram\\javaIOTest\\test.jpg");
int by; while((by = fis.read()) != -1){ fos.write(by); }
long endTime = System.currentTimeMillis(); System.out.println(endTime-startTime); } //基本字节流一次读写一个字节 107610ms public static void method1() throws IOException{ FileOutputStream fos = new FileOutputStream("E:\\javadProgram\\javaIOTest\\1111.avi"); FileInputStream fis = new FileInputStream("C:\\Users\\10923\\Videos\\Captures\\1111.avi");
int by; while((by = fis.read()) != -1){ fos.write(by); }
fos.close(); fis.close(); }
//基本字节流一次读写一个字节数组 143ms public static void method2() throws IOException{ FileOutputStream fos = new FileOutputStream("E:\\javadProgram\\javaIOTest\\1111.avi"); FileInputStream fis = new FileInputStream("C:\\Users\\10923\\Videos\\Captures\\11112.avi");
byte[] bys = new byte[1024]; int len; while((len = fis.read(bys)) != -1){ fos.write(bys,0,len); }
fos.close(); fis.close(); }
//字节缓冲流一次读写一个字节 189ms public static void method3() throws IOException{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\10923\\Videos\\Captures\\1111.avi")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\javadProgram\\javaIOTest\\11113.avi"));
int by; while((by = bis.read()) != -1){ bos.write(by); }
bos.close(); bis.close(); }
//字节缓冲流一次读写一个字节数组 35ms public static void method4() throws IOException{ BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\10923\\Videos\\Captures\\1111.avi")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\javadProgram\\javaIOTest\\11114.avi"));
byte[] bys = new byte[1024]; int len; while((len = bis.read(bys)) != -1){ bos.write(bys,0,len); }
public class BufferStreamDemo { public static void main(String[] args) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("fos.txt"));
public class ConversionStreamDemo1 { public static void main(String[] args) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("fos.txt"),"GBK");
osw.write("行初雾"); osw.close();
InputStreamReader isr = new InputStreamReader(new FileInputStream("fos.txt"),"GBK"); int ch; while((ch = isr.read()) != -1){ System.out.println((char)ch); } } }
public class OutputStreamWriterDemo { public static void main(String[] args) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("fos.txt"));
public class InputStreamReaderDemo { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(new FileInputStream("fos.txt"));
char[] chs = new char[1024]; int len; while((len = isr.read(chs)) != -1){ System.out.println(new String(chs,0,len)); }
isr.close(); } }
案例
复制java文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class CopyJavaDemo01 { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\javadProgram\\javaStudy\\src\\com\\chang\\base\\myIO\\ConversionStreamDemo\\ConversionStreamDemo1.java")); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\javadProgram\\javaIOTest\\copy.java"));
public class CopyJavaDemo02 { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("E:\\\\javadProgram\\\\javaStudy\\\\src\\\\com\\\\chang\\\\base\\\\myIO\\\\ConversionStreamDemo\\\\ConversionStreamDemo1.java"); FileWriter fw = new FileWriter("E:\\\\javadProgram\\\\javaIOTest\\\\copy.java");
public class CopyJavaDemo3 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("E:\\javadProgram\\javaStudy\\src\\com\\chang\\base\\myIO\\ConversionStreamDemo\\ConversionStreamDemo1.java")); BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\javadProgram\\javaIOTest\\copy3.java"));
public class BufferedStreamDemo { public static void main(String[] args) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter("fos.txt"));
public String readLine():读一行文字,结果包含行的的内容的字符串,不包括任何行终止字符,如果流的结尾已经到达,则为null
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class BufferedStreamDemo2 { public static void main(String[] args) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter("fos.txt")); for(int i=0;i<10;i++){ bw.write("hello"+i); bw.newLine(); bw.flush(); }
bw.close();
BufferedReader br = new BufferedReader(new FileReader("fos.txt")); String line; while ((line = br.readLine()) != null){ System.out.println(line); } br.close(); } }
案例
集合到文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class ArrayListToTxtDemo { public static void main(String[] args) throws IOException { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("hello1"); arrayList.add("hello2"); arrayList.add("hello3");
BufferedWriter bw = new BufferedWriter(new FileWriter("fos.txt"));
public class TxtToArrayListDemo { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("fos.txt"));
public class CopyFolderDemo { public static void main(String[] args) throws IOException { File srcFolder = new File("E:\\javadProgram\\javaIOTest\\javaSE");
String srcFolderName = srcFolder.getName();
File destFolder = new File("E:\\javadProgram\\javaIOTest\\javaWeb",srcFolderName);
if(!destFolder.exists()){ destFolder.mkdir(); }
File[] files = srcFolder.listFiles(); for(File srcFile : files){ String srcFileName = srcFile.getName(); File destFile = new File(destFolder,srcFileName); copyFile(srcFile,destFile); } } private static void copyFile(File srcFile,File destFile) throws IOException{ BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] bys = new byte[1024]; int len; while((len = bis.read(bys)) != -1){ bos.write(bys,0,len); } bis.close(); bos.close(); } }
//总结:注意,线程开启不一定立即执行,由CPU调度执行 public class ThreadDemo1 extends Thread { @Override public void run() { for (int i = 0; i < 200; i++) { System.out.println("run------------" + i); } }
public static void main(String[] args) { ThreadDemo1 threadDemo1 = new ThreadDemo1(); threadDemo1.start(); for (int i = 0; i < 1000; i++) { System.out.println("main-" + i); } } }
@Override public void run() { WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(url,name); System.out.println("下载了文件:" + name); }
public static void main(String[] args) { ThreadDemo2 t1 = new ThreadDemo2("https://bkimg.cdn.bcebos.com/pic/730e0cf3d7ca7bcb3700f79abe096b63f624a80f?x-bce-process=image/resize,m_lfit,w_220,limit_1/format,f_auto","E:\\javadProgram\\javaIOTest\\1.jpg"); ThreadDemo2 t2 = new ThreadDemo2("https://bkimg.cdn.bcebos.com/pic/730e0cf3d7ca7bcb3700f79abe096b63f624a80f?x-bce-process=image/resize,m_lfit,w_220,limit_1/format,f_auto","2.jpg"); ThreadDemo2 t3 = new ThreadDemo2("https://bkimg.cdn.bcebos.com/pic/730e0cf3d7ca7bcb3700f79abe096b63f624a80f?x-bce-process=image/resize,m_lfit,w_220,limit_1/format,f_auto","3.jpg");
public class ThreadDemo3 implements Runnable{ @Override public void run() { for (int i = 0; i < 200; i++) { System.out.println("run----------" + i); } }
public static void main(String[] args) { ThreadDemo3 threadDemo3 = new ThreadDemo3();
new Thread(threadDemo3).start();
for (int i = 0; i < 1000; i++) { System.out.println("main--" + i); } } }
public class ThreadDemo6 implements Callable<Boolean> { private String url; //网络图片地址 private String name; //保存的文件名
public ThreadDemo6(String url,String name){ this.name = name; this.url = url; } @Override public Boolean call(){ WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(url,name); System.out.println("下载了文件:" + name); return true; }
public static void main(String[] args) throws ExecutionException, InterruptedException { ThreadDemo6 t1 = new ThreadDemo6("https://bkimg.cdn.bcebos.com/pic/730e0cf3d7ca7bcb3700f79abe096b63f624a80f?x-bce-process=image/resize,m_lfit,w_220,limit_1/format,f_auto","E:\\javadProgram\\javaIOTest\\1.jpg"); ThreadDemo6 t2 = new ThreadDemo6("https://bkimg.cdn.bcebos.com/pic/730e0cf3d7ca7bcb3700f79abe096b63f624a80f?x-bce-process=image/resize,m_lfit,w_220,limit_1/format,f_auto","E:\\javadProgram\\javaIOTest\\2.jpg"); ThreadDemo6 t3 = new ThreadDemo6("https://bkimg.cdn.bcebos.com/pic/730e0cf3d7ca7bcb3700f79abe096b63f624a80f?x-bce-process=image/resize,m_lfit,w_220,limit_1/format,f_auto","E:\\javadProgram\\javaIOTest\\3.jpg");
//创建执行服务 ExecutorService ser = Executors.newFixedThreadPool(3);
//3.静态内部类 static class Like2 implements ILike{ @Override public void lambda() { System.out.println("i like lambda2"); } }
public static void main(String[] args) { ILike like = new Like(); like.lambda();
like = new Like2(); like.lambda();
//4.局部内部类 class Like3 implements ILike{ @Override public void lambda() { System.out.println("i like lambda3"); } } like = new Like3(); like.lambda();
//5.匿名内部类 like = new ILike() { @Override public void lambda() { System.out.println("i like lambda4"); } }; like.lambda();
//6.用lambda简化 like = ()-> { System.out.println("i like lambda5"); }; like.lambda(); } } //1.定义一个函数式接口 interface ILike{ void lambda(); }
//2.实现类 class Like implements ILike{ @Override public void lambda() { System.out.println("i like lambda"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class LambdaDemo2 { public static void main(String[] args) { ILove love = null; //简化1.参数类型 love = (a)->{ System.out.println("i love you ->" + a); }; //简化2.简化括号 love = a -> { System.out.println("i love you ->" + a); }; //简化3.去掉花括号 love = a -> System.out.println("i love you ->" + a); love.love(520); } } interface ILove{ void love(int a); }
public class StaticProxy { public static void main(String[] args) { // WeddingCompany weddingCompany = new WeddingCompany(new You()); // weddingCompany.HappyMarry(); You you = new You();
new Thread( ()-> System.out.println("aaa")).start();
new WeddingCompany(you).HappyMarry(); } }
interface Marry{ void HappyMarry(); } class You implements Marry{ @Override public void HappyMarry() { System.out.println("HAPPYMARRY"); } } class WeddingCompany implements Marry{ private Marry target;
public WeddingCompany(Marry target) { this.target = target; }
@Override public void HappyMarry() { before(); this.target.HappyMarry(); after(); }
public class TestStop implements Runnable{ //1.设置一个标志位 private boolean flag = true; @Override public void run() { int i = 0; while (flag){ System.out.println("run.......Thread" + i++); } }
//2.设置一个公开的方法停止线程,转换标志位 public void stop(){ this.flag = false; }
public static void main(String[] args) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i = 0; i < 1000; i++) { System.out.println("main"+i); if(i==900){ testStop.stop(); System.out.println("线程该停止了"); } } } }
public static void main(String[] args) throws InterruptedException { Date startTime = new Date(System.currentTimeMillis()); while(true){ Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); startTime = new Date(System.currentTimeMillis()); } } public static void tenDown() throws InterruptedException { int num = 10; while(true){ Thread.sleep(1000); System.out.println(num--); if(num<=0) break; } } }
线程礼让
礼让线程,让当前正在执行的线程暂停,但不阻塞
将线程从运行状态转为就绪状态
让cpu重新调度,礼让不一定成功!看CPU心情
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class TestYield { public static void main(String[] args) { MyYield myYield = new MyYield();
new Thread(myYield,"a").start(); new Thread(myYield,"b").start(); } } class MyYield implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"线程开始执行"); Thread.yield(); System.out.println(Thread.currentThread().getName()+"线程停止执行"); } }
public class TestPriority { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority); Thread t2 = new Thread(myPriority); Thread t3 = new Thread(myPriority); Thread t4 = new Thread(myPriority); Thread t5 = new Thread(myPriority); Thread t6 = new Thread(myPriority);
public class TextDaemon { public static void main(String[] args) { God god = new God(); You you = new You();
Thread thread = new Thread(god); thread.setDaemon(true);
thread.start();
new Thread(you).start(); } }
//上帝 class God implements Runnable{ @Override public void run() { while(true) System.out.println("上帝保佑着你"); } }
//你 class You implements Runnable{ @Override public void run() { for (int i = 0; i < 36500; i++) { System.out.println("你一生都开心的活着"); } System.out.println("byebye"); } }
public class UnsafeList { public static void main(String[] args) { List<String> list = new ArrayList<>(); for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } System.out.println(list.size());
public class TestPC2 { public static void main(String[] args) { TV tv = new TV(); new Player(tv).start(); new Watcher(tv).start(); } }
//生产者--> 演员 class Player extends Thread{ TV tv; public Player(TV tv){ this.tv=tv; }
@Override public void run() { for (int i = 0; i < 20; i++) { if(i%2==0) this.tv.play("快乐大本营播放中"); else this.tv.play("抖音:记录美好生活"); } } } //消费者--> 观众 class Watcher extends Thread{ TV tv; public Watcher(TV tv){ this.tv=tv; }
@Override public void run() { for (int i = 0; i < 20; i++) { tv.watch(); } } }
//产品--> 节目 class TV{ //演员表演,观众等待 T //观众观看,演员等待 F String voice; //表演的节目 boolean flag = true;
//表演 public synchronized void play(String voice){ if (!flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
public class Demo1 { //注解可以显示复制,如果没有默认值,则必须给注解赋值 @MyAnnotation(age = 10,name = "xingchuwu") public void test(){} @MyAnnotation2("xingchuwu") public void test2(){} }
public class Deni2 { public static void main(String[] args) throws ClassNotFoundException { Person person = new Student(); System.out.println("这个人是:" + person.name);
//方式一:通过对象获得 Class c1 = person.getClass(); System.out.println(c1.hashCode());
//方法二:forname获得 Class c2 = Class.forName("com.chang.base.myReflection.Student"); System.out.println(c2.hashCode());
//方式三:通过类名.class获得 Class c3 = Student.class; System.out.println(c3.hashCode());
//方式四:基本内置类型的包装类都有一个Type属性 Class c4 = Integer.TYPE; System.out.println(c4.hashCode());
//获得父类类型 Class c5 = c1.getSuperclass(); System.out.println(c5); }
}
class Person{ String name;
public Person() { }
public Person(String name) { this.name = name; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } }
class Student extends Person{ public Student() { this.name = "Student"; } }
class Teacher extends Person{ public Teacher(){ this.name = "Teacher"; } }
public class Demo3 { public static void main(String[] args) { Class c1 = Object.class; //类 Class c2 = Comparable.class; //接口 Class c3 = String[].class; //一维数组 Class c4 = int[][].class; //二维数组 Class c5 = Override.class; //注解 Class c6 = ElementType.class; //枚举 Class c7 = Integer.class; //基本数据类型 Class c8 = void.class; //void Class c9 = Class.class; //Class
//只有元素类型与维度一样,就是同一个Class int[] a = new int[10]; int[] b = new int[100]; System.out.println(a.getClass().hashCode()); System.out.println(b.getClass().hashCode()); } }
public class Demo10 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class c1 = Class.forName("com.chang.base.myReflection.Student2");
public class Demo1 { public static void main(String[] args) { B b = new B(); b.test1(); //实现方法一:直接调用接口的默认方法 C c = new C(); c.test1(); //实现方法二:重写接口的默认方法 } }
interface A{ public default void test1(){ System.out.println("我是接口A的默认方法"); } }
class B implements A{
}
class C implements A{ @Override public void test1() { System.out.println("我是C类重写的默认方法"); } }
静态方法
为了方便接口扩展,JDK 8为接口新增了静态方法
静态方法不能重写
格式如下:
1 2 3 4 5
interface 接口名{ 修饰符 static 返回值类型 方法名(){ 代码; } }
1 2 3 4 5 6 7 8 9 10 11
public class Demo2 { public static void main(String[] args) { A1.test1(); } }
interface A1{ public static void test1(){ System.out.println("我是接口A1的静态方法"); } }