本文介绍javaSE相关知识
目录
java起步
基本数据类型
数据类型转换
运算符
流程控制和循环语句
方法
类
接口
泛型
引用类型
代码块
正则表达式
IO流
线程
MySQL Connector/J 的基本使用
网络编程
-
- 简单DOS命令
cd.. 返回上一级目录 cd \ 返回到根目录 d: 切换到d盘 dir 列出目录和文件 cls 清楚DOS窗口 ipconfig 列出ip配置
- java基础名词
jdk java开发环境 jre java运行环境 jvm java跨平台虚拟机 jvm包含于jre,jre包含于jdk
- java编译和运行流程
第一步,编写HelloWorld.java文件,输入如下内容 文件名和类名必须一致 public class HelloWorld{ public static void main(String[] args){ System.out.println("HelloWorld"); } } 第二步,找到java安装目录下的java.exe和javac.exe 创建两个快捷方式,放到源文件目录下 运行 javac -encoding UTF-8 HelloWorld.java 编译文件,生成 HelloWorld.class 文件 运行 java HelloWorld 运行编译后的class文件 除了创建快捷方式外,还可以设置系统环境变量,在path下面指定目录 C:\Program Files\Java\jdk1.8.0_131\bin;
- Eclipse快捷键
alt + / 代码快速补全,导包 ctrl + shift + F 格式化代码 ctrl + / 单行注释,取消注释 ctrl + shift + / 多行注释 ctrl + shift + \ 取消多行注释 ctrl + shift + o 快速导包 alt + 上下箭头 移动代码行 ctrl + alt + 上下箭头 快速复制一行代码 ctrl + D 删除当前行 ctrl + 1 错误提示 ctrl + T 查看类的继承关系 F6 单步执行 F5 进入调试语句内部
- Eclipse相关操作
使用 /** 写的文档注释,可以使用Eclipse中的Export导出javadoc 开发的package可以使用Eclipse的Export导出jar文件 将导出的jar文件引用到项目中来,遵循如下几步 在src目录下新建一个lib目录 将jar文件复制到lib中 右键jar文件buildpath -> add new path 在程序中import进来相关文件即可
- java静态导入
import static java.lang.System.out; out.println(1);
-
数据类型 字节数 范围 备注 byte 1 -128~127 short 2 -32768~32767 int 4 -2147483648~2147483648 整数默认是int long 8 -2^63 ~ 2^63 - 1 超出int范围的值,需要在末尾添加L否则报错 float 4 -3.40310^38 ~ -3.40310^38 可以在末尾加上F double 8 -1.79810^308 ~ 1.79810^308 浮点默认是double,可以在末尾加上D char 2 表示一个字符 boolean 1 true 或者 false -
低精度的类型可以自动转化给高精度的类型,反之不可以,此时必须强制类型转换,如下 long a = 111; int b = (int)a; char类型和int类型之间的转换 char转int char cr = 'a'; int i = cr; System.out.println(i); // 97 输出字符的ascll码 int转char int i = 99; char cr = (char)i; System.out.println(cr); // c 输出ascll码对应的字符
-
算术运算符 + - * / % ++ -- 赋值运算符 = += -= *= /= %= 比较运算符 == != < > <= >= 逻辑运算符 & 与 | 或 ^ 两边操作数是相同的就是false反之true ! 非 && 短路与 || 短路或 三元运算符 a>b?a:b
-
流程控制 if...else... if...else if...else... i>j?i:j switch(Expression1){ // Expression1和Expression2相等执行case case Expression2: ... break; case Expression3: case Expression4: ... break; default: ... break; } 循环语句 while(true){...} do{...}while(true) for(int i = 0; i < 10; i++){...} 循环控制关键字 break 用于终止循环 跳出外层循环 name:for(int i = 0; i < 3; i++){ System.out.println("aa"); for(int j = 0; j < 2; j++){ System.out.println("bb"); break name; } } continue 用于跳出本次循环
-
方法声明 public int fn(int a) { return a; } 方法重载:同名方法,其中参数个数、数据类型和顺序有一个不同就是不同的方法 可变参数 public static void main(String[] args) { fn(1,2,3); } public static void fn(int...arr) { for (int i : arr) { System.out.println(i); } }
-
- java中的修饰关键字
public 公开 protected 父类和子类可用 default 不写权限关键字,默认是default,只能在当前package下是使用 private 本类可用 final 表示固定不变的 final修饰的类不能被继承 final修饰的方法不能被子类重写 final修饰的变量就是常量,不能修改 final int j = 11; static 表示静态,只能通过类本身访问
- 不创建package
java中的一个文件就是一个类,你可以选择定义一个文件比如Test.java public class Test { int a = 111; // 属性 } 在主方法中使用 public static void main(String[] args) { Test test = new Test(); System.out.println(test.a); }
- 创建package
java中也可以通过eclipse创建package,package的作用就相当于是命名空间,package的名称如Demo.test1 在此package中创建一个类Test1 package Demo.test1; public class Test1 { public int i; public void fn() { int i = 444; System.out.println(i + " " + this.i); // this表示本类实例,super表示父类实例 } } 在此package中创建另外一个类Test2 package Demo.test1; public class Test2 { public static void main(String[] args) { Test1 t1 = new Test1(); t1.i = 333; t1.fn(); } }
- 构造函数
单个构造函数 public class demo2 { public int a; public demo2 (int i) { this.a = i; } } 多个构造函数 public class demo2 { public int a; public demo2() { this(111); // 只能写在第一行 } public demo2 (int i) { this.a = i; } }
- 类的继承
创建Test3类 package Demo.test1; public class Test3 { public String str = "aaa"; } 创建Test1类继承Test3 package Demo.test1; public class Test1 extends Test3 { public void fn() { System.out.println(str); } } java中子类重写父类的方法,直接写方法就可以了,子类中的重写的方法的权限必须大于或者等于父类方法的权限 子类继承父类,需要父类有无参数的构造函数 默认情况下,类不写构造函数会自动编译一个无参数构造函数,除非人为指定构造函数,如下 public class demo3 { public demo3(int i) { } } public class demo2 extends demo3 { public int a; public demo2() { // super(); // 默认情况下不写super,系统会自动编程成 super(),所以父类不包含无参数构造函数就会报错 super(111); // super只能写在第一行 } }
- 抽象类
抽象类,就是一个风马牛不相及的东西的共性提取,不能实例化 abstract public class Test3 { public String str = "aaa"; public abstract void fn(); // 抽象方法只能定义,具体实现必须在子类中完成 } 抽象方法不能和 private,final,static 一起使用
- instanceof运算符
用来判断一个对象是否是一个类的实例 demo2 test = new demo2(); boolean b = test instanceof demo2;
- 内部类
public class demo3 { int i = 1; public class demo4 { int i = 2; public void fn() { int i = 3; System.out.println(i); // 3 System.out.println(this.i); // 2 System.out.println(demo3.this.i); // 1 } } } 使用此内部类 demo3.demo4 test1 = new demo3().new demo4(); test1.fn();
- equals
引用类型比较的地址是否相同,值类型比较值是否相同 demo3 test1 = new demo3(); demo3 test2 = new demo3(); boolean b = test1.equals(test2); 可以重写equals方法,实现自定义比较 public boolean equals (Object obj) { demo3 d3 = (demo3)obj; return this.a = obj.a; }
-
java中的接口也是单独使用一个文件定义,接口的定义相当简单,权限固定为public,变量只能定义为常量,方法只能抽象 接口成员只能是如下几种情况 public interface MyInterface { public abstract void fn(); // 只能使用public修饰符 abstract void fn1(); // 效果和上面写法一致 public static final int a = 1; // 表示静态常量 String b = "bb"; // 效果和上面写法一致 } 接口使用 public class Test1 implements MyInterface{ public void fn() { System.out.println(MyInterface.a); } ... } 接口的简便使用方法 定义一个接口 public interface MyInterface { public abstract void method(); } 使用接口 MyInterface it = new MyInterface() { public void method() { System.out.println("aaa"); } }; it.method(); 抽象类也可以使用这种方式来使用 接口可以继承其他接口,使用extends关键字
-
- 泛型限定
泛型类型通配符限定 public void fn(ArrayList<? extends String> arr) { }
-
- 包装类
每个基本数据类型都会有一个包装类与之对应,用来提供更为强大的功能 包装类如下 Byte Short Integer Long Float Double Character Boolean 使用 将字符串转化成对应的基本数据类型,如 boolean bl = Boolean.parseBoolean("false"); int i = Integer.parseInt("11"); 将基本数据类型转化成字符串 String str = Integer.toString(3); 使用包装类构造函数 Integer it = new Integer("5555"); int i = it.intValue(); 基本数据类型自动装箱和拆箱 Integer i = 11; // 装箱 i++; // 拆箱
- String类型
字符串一旦创建在堆中就不可变 字符串声明 String str = "你好"; String str = new String("abc"); 字符串比较 String str1 = new String("abc"); String str2 = "abc"; System.out.println(str1.equals(str2)); -> true 比较字符串中每个字符是否相等 System.out.println(str1 == str2); -> false
- StringBuffer类
可变字符串 StringBuffer str = new StringBuffer("aa"); str.append("bb"); System.out.println(str); // aabb
- StringBuilder类,和StringBuffer类使用方式一样,速度更快
- Scanner类
import java.util.Scanner; // 导入第三方包 public class HelloWorld { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 创建Scanner实例接受用户输入 while(true) { // int i = sc.nextInt(); 读取整数 String i = sc.next(); 读取字符串 System.out.println(i + "a"); } } }
- Random类
import java.util.Random; Random rd = new Random(); // System.out.println(rd.nextBoolean()); // 产生布尔随机数 // System.out.println(rd.nextInt()); // 产生任意随机整数 System.out.println(rd.nextInt(10)); // 产生 大于等于0,小于10的整数
- 一维数组
int[] arr = new int[3]; 声明数组 int[] arr = new int[]{1,2,3}; 声明并赋值 int[] arr = {1,2,3}; 声明并赋值简写 arr[0] = 1; 元素赋值 arr.length 数组长度 数组遍历 for (int item : arr) { System.out.println(item); } 注意:超出索引范围,运行会报错
- 二维数组
int[][] arr = new int[2][3]; 声明 int[][] arr = {{1,2,3}, {4,5,6}}; 声明并赋值 arr[1][2] 访问元素 遍历元素 for (int[] items : arr) { for (int item : items) { System.out.println(item); } }
- Arrays类
sort升序排序 int[] arr = {1,4,5,1,2,3,1}; Arrays.sort(arr); binarySearch二分查找 此法采用二分法找数组元素,适合大量不重复数组的快速查找,找不到返回负数 int[] arr = {1,4,5,1,2,3,1}; int index = Arrays.binarySearch(arr, 1); // 3 toString序列化 int[] arr = {1,4,5,1,2,3,1}; String str = Arrays.toString(arr); // [1, 4, 5, 1, 2, 3, 1]
- ArrayList集合
顺序表,增删慢,查询快 ArrayList是有序可重复集合 用来存储引用类型,基本类型的引用类型(包装类)对应如下 Byte Short Integer Long Float Double Character Boolean 导入 import java.util.ArrayList; 声明 ArrayList<Integer> arr = new ArrayList<Integer>(); 追加元素 arr.add(11); 插入元素 arr.add(1, 33); 修改元素 arr.set(0, 33); 移除元素 arr.remove(0); 清空集合 arr.clear(); 获取元素 arr.get(0) 获取元素个数 arr.size() 遍历 for (Integer item : arr) { System.out.println(item); } 迭代器 Iterator<Integer> it = arr.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
- LinkedList集合
链表,增删快,查询慢 LinkedList<String> arr = new LinkedList<String>(); arr.add("a"); arr.addLast("c"); arr.addFirst("b"); arr.getFirst(); arr.getLast(); arr.removeFirst(); arr.removeLast(); arr.clear();
- HashSet集合
Hash集合底层数据结构是散列表,所以要求元素必须不重复,避免地址对应冲突 Hash集合访问的直接是数据地址,查询元素最快,增删元素也快 HashSet集合处理地址冲突的方法使用开放定址法 HashSet是无序无重复元素集合 使用方法和ArrayList一致 HashSet<Integer> arr = new HashSet<Integer>();
- LinkedHashSet集合
LinkedHashSet集合处理地址冲突的方法使用链地址法 LinkedHashSet<String> arr = new LinkedHashSet<String>();
- Map集合
存储键值对 HashMap<String, Integer> obj = new HashMap<String, Integer>(); // LinkedHashMap<String, Integer> obj = new LinkedHashMap<String, Integer>(); obj.put("a", 1); obj.put("b", 2); obj.get("a"); 遍历键值对 Set<String> keys = obj.keySet(); for (String key : keys) { System.out.println(key + ":" + obj.get(key)); } 或者 for (String key : obj.keySet()) { System.out.println(key + ":" + obj.get(key)); } 或者 Set<HashMap.Entry<String, Integer>> KeyValues = obj.entrySet(); for (HashMap.Entry<String, Integer> KeyValue : KeyValues) { System.out.println(KeyValue.getKey() + ":" + KeyValue.getValue()); } 或者 for (HashMap.Entry<String, Integer> KeyValue : obj.entrySet()) { System.out.println(KeyValue.getKey() + ":" + KeyValue.getValue()); }
- Properties类
存储键值对 Properties obj = new Properties(); obj.setProperty("a", "1"); // 设置键值对 obj.setProperty("b", "2"); obj.getProperty("b"); // 获取键值 Set<String> KeyValues = obj.stringPropertyNames(); // 获取键值对 对象持久化存储 读取 public static void main(String[] args) { Properties obj = new Properties(); InputStream in = null; try { in = demo1.class.getClassLoader().getResourceAsStream("demo.txt"); obj.load(in); for (String item : obj.stringPropertyNames()) { System.out.println(item + "|" + obj.getProperty(item)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } } demo.txt文件格式如下 url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false username=root password=123 #c=3 注释 写入 Properties obj = new Properties(); obj.setProperty("name", "叶家伟"); obj.setProperty("age", "18"); obj.setProperty("sex", "女"); FileWriter f = null; try { f = new FileWriter("C:\\Users\\26401\\Desktop\\java\\demo.txt"); obj.store(f, "KeyValue"); } catch (Exception e) { e.printStackTrace(); } finally { try { if(f != null) f.close(); } catch (IOException e) { e.printStackTrace(); } }
- Collections工具类
ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(2); arr.add(3); Collections.shuffle(arr); // 打乱数组 int index = Collections.binarySearch(arr, 2); // 二分查找
- Date类
System.out.println(System.currentTimeMillis()); // 当前时间毫秒数 Date time = new Date(); // 本地日期 time.getTime() // 当前毫秒值 time.setTime(0) // 根据毫秒值设置日期
- SimpleDateFormat类
根据格式将日期对象转成字符串 Date time = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS"); String str = sf.format(time); // 2018-02-10-21-24-29-043 根据格式将字符串转成日期对象 public static void main(String[] args) throws Exception { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); Date time = sf.parse("2001-08-09"); System.out.println(time); }
- Calendar抽象类
用来获取日期的具体部分 Calendar cd = Calendar.getInstance(); int time = cd.get(Calendar.YEAR); // 获取年份 int time = cd.get(Calendar.MONTH) + 1; // 获取月份 int time = cd.get(Calendar.DAY_OF_MONTH); // 获取天 用来设置日期的具体部分 Calendar cd = Calendar.getInstance(); cd.set(Calendar.MONTH, 8); // 设置月份为9月 cd.set(2001, 3, 3); cd.add(Calendar.DAY_OF_MONTH, 2); // 时间偏移 Date time = cd.getTime(); // 将Calendar转化成Date类
- System类的一些方法
System.exit(0); // 正常终止jvm虚拟机 垃圾回收 public class demo1 { public static void main(String[] args) { new demo1(); System.gc(); // 调用gc会自动调用finalize方法 } public void finalize() { System.out.println("a"); } } 系统属性获取 Properties pt = System.getProperties(); String str = pt.getProperty("java.runtime.name"); // Java(TM) SE Runtime Environment 数组复制 int[] arr = {1,2,3,4,5}; int[] target = new int[5]; System.arraycopy(arr, 2, target, 0, 1); // [3] 将arr数组中的一部分复制到target数组中 查看代码执行时间 long start = System.currentTimeMillis(); ... long end = System.currentTimeMillis(); System.out.println(end - start);
- Math类
Math.abs(-1) // 绝对值 Math.ceil(1.1) // 向上取整 Math.floor(1.1) // 向下取整 Math.random() // 随机数 Math.round(4.61) // 5 取整,四舍五入
- 异常处理
public static void main(String[] args) throws Exception { throw new Exception("错啦"); } try { } catch (Exception e) { throw e; } finally { }
- BigInteger类
超过long的大数据运算,整数计算 BigInteger bi = new BigInteger("43332142354254678654"); BigInteger bi1 = bi.add(bi); // 相加 BigInteger bi1 = bi.subtract(bi); // 相减 BigInteger bi1 = bi.multiply(bi); // 相乘 BigInteger bi1 = bi.divide(bi); // 相除
- BigDecimal类
超大浮点数运算 BigDecimal bd = new BigDecimal("0.01"); BigDecimal bd1 = bd.add(bd); // 相加 BigDecimal bd1 = bd.subtract(bd); // 相减 BigDecimal bd1 = bd.multiply(bd); // 相乘 相除 能够除尽的数 BigDecimal bd1 = bd.divide(bd); 除不尽,保留小数 BigDecimal bd = new BigDecimal("0.01"); BigDecimal bd1 = new BigDecimal("0.03"); BigDecimal bd2 = bd.divide(bd1, 2); 除不尽,保留小数,指定保留模式 BigDecimal bd2 = bd.divide(bd1, 2, BigDecimal.ROUND_HALF_DOWN); // 四舍五入
-
public class demo3 { public demo3() { { // 构造函数代码块 System.out.println(1); } } { // 构造代码块,构造函数之前执行 System.out.println(2); } static { // 静态代码块,只会执行一次,构造代码块之前执行 System.out.println(3); } } demo3 test = new demo3(); demo3 test1 = new demo3(); 执行结果: 3 2 1 2 1
-
匹配规则 [abc] abc其中一个 [^abc] abc之外的一个 [a-z] a和z之间的一个 . 表示任意字符 \d 表示一个数字 \D 非数字 \w 表示a-zA-Z0-9_ \W 非a-zA-Z0-9_ ^ 开头 $ 结尾 \b 英文单词边界 ? 一次或者0次 * 零次或者多次 + 一次或者多次 {n} 出现制定n次 {n,} 至少n次 {n,m} >=n <=m 次 正在表达式在字符串方法中的使用 matches方法 判断字符串是否满足正则匹配 String str = "abc"; boolean b = str.matches("[a].*"); split方法 根据正则匹配的规则分隔字符串 String str = "abc"; String[] arr = str.split("[b]"); // [a, c] replaceAll方法 将匹配的字符串替换成其他字符 String str = "abc"; String str1 = str.replaceAll("[\\w]", "1"); // 111
-
- File类
String separator = File.pathSeparator; // 文件路径分隔符 String separator = File.separator; // 文件名分隔符 File file = new File("C:\\Users\\26401\\Desktop\\java"); File file = new File("C:\\Users\\26401\\Desktop\\java", "demo.txt"); File fileFather = new File("C:\\Users\\26401\\Desktop\\java"); File file = new File(fileFather, "demo.txt"); try { boolean b = file.createNewFile(); // 创建文件 boolean b = file.mkdir(); // 创建文件夹 boolean b = file.mkdirs(); // 创建多级文件夹 boolean b = file.delete(); // 删除文件或者文件夹 String s = file.getName(); // 获取文件或者文件夹名 String s = file.getPath(); // 获取文件或者文件夹路径 long s = file.length(); // 获取文件大小 String s = file.getAbsolutePath(); // 获取文件或者文件夹绝对路径 File s = file.getAbsoluteFile(); // 获取文件或者文件夹绝对路径 File s = file.getParentFile(); // 获取文件或者文件夹父路径 boolean b = file.exists(); // 判断文件或者文件夹是否存在 boolean b = file.isDirectory(); // 判断文件夹是否存在 boolean b = file.isFile(); // 判断文件是否存在 String[] arr = file.list(); // 获取文件夹下的文件名和文件夹名 File[] arr = file.listFiles(); // 获取文件夹下的文件和文件夹 } catch (Exception e) { e.printStackTrace(); }
- FileFilter
过滤文件 public class demo1 extends assist { public static void main(String[] args) { File fileFather = new File("C:\\Users\\26401\\Desktop\\java"); File file = new File(fileFather, "demo"); try { File[] arr = file.listFiles(new myFilter()); for (File file2 : arr) { System.out.println(file2); } } catch (Exception e) { e.printStackTrace(); } } } class myFilter implements FileFilter { public boolean accept(File pathname) { String name = pathname.getName(); return name.endsWith(".txt"); } }
- 递归遍历所有目录和文件
static void GetAllFileAndDirectory(File filename) { File[] arr = filename.listFiles(); for (File f : arr) { if(f.isDirectory()) { GetAllFileAndDirectory(f); }else { System.out.println(filename); System.out.println(f); } } }
- IO流
字节流 写入数据 FileOutputStream f = null; try { f = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt"); // 创建并覆盖文件 f = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt", true); // 续写文件流 f.write(100); // 写一个字节 byte[] bs = {49, 48, 48}; f.write(bs); // 写字节数组 f.write("abc".getBytes()); f.write("a\r\nb\r\nc".getBytes()); // 换行 } catch (Exception e) { e.printStackTrace(); } finally { try { if(f != null) f.close(); } catch (IOException e) { e.printStackTrace(); } } 读取数据 一个一个字节读 FileInputStream f = null; try { f = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt"); int i; while((i = f.read()) != -1) { System.out.println((char)i); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(f != null) f.close(); } catch (IOException e) { e.printStackTrace(); } } 利用字节数组缓冲区读 FileInputStream f = null; try { f = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt"); int len; byte[] b = new byte[1]; while((len = f.read(b)) != -1) { System.out.println(new String(b, 0, len)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(f != null) f.close(); } catch (IOException e) { e.printStackTrace(); } } 复制文件 FileInputStream fi = null; FileOutputStream fo = null; try { fi = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt"); fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo1.txt"); int len; byte[] b = new byte[1]; while((len = fi.read(b)) != -1) { fo.write(b, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(fi != null || fo != null) { fi.close(); fo.close(); }; } catch (IOException e) { e.printStackTrace(); } } 字符流 GBK编码流 写 FileWriter fo = null; try { fo = new FileWriter("C:\\Users\\26401\\Desktop\\java\\demo\\demo1.txt"); byte[] b = {'a', 'b', 'c'}; fo.write(new String(b, 0, 2, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fo != null) { fo.flush(); fo.close(); }; } catch (IOException e) { e.printStackTrace(); } } 读 FileReader fo = null; try { fo = new FileReader("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt"); char[] b = new char[1]; while((fo.read(b)) != -1) { System.out.println(new String(b)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(fo != null) { fo.close(); }; } catch (IOException e) { e.printStackTrace(); } } 编码转换流 可以自定义编码 写 FileOutputStream fo = null; OutputStreamWriter fow = null; try { fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fow = new OutputStreamWriter(fo, "UTF-8"); fow.write("叶家伟"); fow.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fow != null) { fow.flush(); fow.close(); }; } catch (IOException e) { e.printStackTrace(); } } 读 FileInputStream fo = null; InputStreamReader fow = null; try { fo = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fow = new InputStreamReader(fo, "UTF-8"); char[] c = new char[1024]; int len = fow.read(c); System.out.println(new String(c, 0, len)); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fow != null) { fow.close(); }; } catch (IOException e) { e.printStackTrace(); } }
- 缓冲流
字节流 写 FileOutputStream fo = null; BufferedOutputStream fob = null; try { fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fob = new BufferedOutputStream(fo); fob.write("叶家伟".getBytes()); fob.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fo != null) { fob.flush(); fob.close(); }; } catch (IOException e) { e.printStackTrace(); } } 读 FileInputStream fo = null; BufferedInputStream fob = null; try { fo = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fob = new BufferedInputStream(fo); byte[] b = new byte[2]; int len = 0; while((len = fob.read(b)) != -1) { System.out.println(new String(b, 0, len)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(fob != null) { fob.close(); }; } catch (IOException e) { e.printStackTrace(); } } 字符流 写 FileWriter fo = null; BufferedWriter fob = null; try { fo = new FileWriter("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fob = new BufferedWriter(fo); fob.write("叶家伟"); fob.newLine(); // 换行 fob.write("叶家伟"); fob.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fo != null) { fob.flush(); fob.close(); }; } catch (IOException e) { e.printStackTrace(); } } 读 FileReader fo = null; BufferedReader fob = null; try { fo = new FileReader("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fob = new BufferedReader(fo); char[] b = new char[20]; while((fob.read(b)) != -1) { System.out.println(new String(b)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(fob != null) { fob.close(); }; } catch (IOException e) { e.printStackTrace(); } }
- 对象流
写对象 public class demo1 extends assist { public static void main(String[] args) { FileOutputStream fo = null; ObjectOutputStream foo = null; try { fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); foo = new ObjectOutputStream(fo); Demo d = new Demo("叶家伟", 18, "女"); foo.writeObject(d); } catch (Exception e) { e.printStackTrace(); } finally { try { if(foo != null) foo.close(); } catch (IOException e) { e.printStackTrace(); } } } } class Demo implements Serializable { String Name; int Age; static transient String Sex; // transient禁止实例序列化,static是类属性,实例无法序列化 static final long serialVersionUID = 1243543523L; // 自定义类唯一序列号标识 public void fn() { System.out.println(this.Name + "|" + this.Age + "|" + this.Sex); } public Demo(String Name, int Age, String Sex) { this.Name = Name; this.Age = Age; this.Sex = Sex; } } 读对象 FileInputStream fi = null; ObjectInputStream fii = null; try { fi = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fii = new ObjectInputStream(fi); Demo d = (Demo)fii.readObject(); System.out.println(d.Age); } catch (Exception e) { e.printStackTrace(); } finally { try { if(fii != null) fii.close(); } catch (IOException e) { e.printStackTrace(); } }
- 打印流
字符流 写 PrintWriter pw = null; try { pw = new PrintWriter("C:\\Users\\26401\\Desktop\\java\\demo.txt"); pw.println("affsddfq"); pw.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if(pw != null) pw.close(); } FileOutputStream fo = null; PrintWriter pw = null; try { fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); pw = new PrintWriter(fo); pw.println("wrqr3"); pw.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if(pw != null) pw.close(); } FileOutputStream fo = null; PrintWriter pw = null; try { fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt"); pw = new PrintWriter(fo, true); // 开启,省略flush语句 pw.println("erere"); } catch (Exception e) { e.printStackTrace(); } finally { if(pw != null) pw.close(); } 复制文件 BufferedReader fo = null; FileWriter fw = null; FileReader fr = null; PrintWriter pw = null; String line = null; try { fr = new FileReader("C:\\Users\\26401\\Desktop\\java\\demo.txt"); fo = new BufferedReader(fr); fw = new FileWriter("C:\\Users\\26401\\Desktop\\java\\demo1.txt"); pw = new PrintWriter(fw, true); while((line = fo.readLine()) != null) { pw.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { if(pw != null) { pw.close(); try { if(fo != null) fo.close(); } catch (IOException e) { e.printStackTrace(); } } }
-
- 创建线程
继承Thread类实现 public class demo1 { public static void main(String[] args) { assist a = new assist(); a.setName("我的子线程"); // 设置子线程名称 a.start(); for(int i = 0; i < 100; i++) { System.out.println("主线程" + i); } Thread t = Thread.currentThread(); System.out.println("主线程名称" + t.getName()); // 获取主线程名称 } } public class assist extends Thread { public void run () { for(int i = 0; i < 100; i++) { try { Thread.sleep(1000); // 线程休眠 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子线程" + i); } } System.out.println("子线程名称" + super.getName()); // 获取子线程名称 } 继承Runnable接口实现 public class demo1 { public static void main(String[] args) { assist a = new assist(); new Thread(a).start(); for(int i = 0; i < 100; i++) { System.out.println("主线程" + i); } } } public class assist implements Runnable { public void run () { for(int i = 0; i < 100; i++) { System.out.println("子线程" + i); } } } 匿名内部类实现 new Thread() { public void run() { for(int i = 0; i < 100; i++) { System.out.println("子线程->" + i); } } }.start(); 或者 new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 100; i++) { System.out.println("子线程->" + i); } } }).start();
- 线程池
基本用法 ExecutorService es = Executors.newFixedThreadPool(2); es.submit( new Runnable() { @Override public void run() { for(int i = 0; i < 100; i++) { System.out.println("子线程->" + i); } } } ); for(int i = 0; i < 100; i++) { System.out.println("主线程->" + i); } 利用Callable接口实现返回值 ExecutorService es = Executors.newFixedThreadPool(2); Future<String> f1 = es.submit( new Callable<String>() { public String call() { for(int i = 0; i < 100; i++) { System.out.println("子线程1->" + i); } return "1执行完了"; } } ); Future<String> f2 = es.submit( new Callable<String>() { public String call() { for(int i = 0; i < 100; i++) { System.out.println("子线程2->" + i); } return "2执行完了"; } } ); try { System.out.println(f1.get()); System.out.println(f2.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }
- 同步多线程
public class demo1 { public static void main(String[] args) { assist a = new assist(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); new Thread(a).start(); } } 使用同步关键字解决多线程共享数据冲突问题 public class assist implements Runnable { int count = 100; Object obj = new Object(); public void run () { while(count > 0) { synchronized (obj) { if(count > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "-> " + --count); } } } } } 使用同步方法解决 public class assist implements Runnable { int count = 100; public void run () { while(count > 0) { fn(); } } public synchronized void fn () { // 同步锁是实例对象,如果添加static关键字修饰,同步锁就是本类 if(count > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "-> " + --count); } } } 使用lock解决同步问题 public class assist implements Runnable { int count = 100; private Lock lock = new ReentrantLock(); public void run () { while(count > 0) { lock.lock(); if(count > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "-> " + --count); } lock.unlock(); } } }
- 线程等待与唤醒
synchronized (this) { this.notify(); // 唤醒 try { this.wait(); // 等待 } catch (InterruptedException e) { e.printStackTrace(); } }
-
- 基本示例
public class demo1 { static Connection con = null; static Statement st = null; static ResultSet rs = null; public static void main(String[] args) { try { String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"; String username = "root"; String password = "123"; con = DriverManager.getConnection(url, username, password); st = con.createStatement(); /* 更新操作 * * String sql = "insert into event values (\"xiaohuang\",\"1920-12-09\",\"birthday\",\"First birthday\");"; * int i = st.executeUpdate(sql); * * * 插入操作 * * String sql = "SELECT * FROM test.event;"; * rs = st.executeQuery(sql); * while(rs.next()) { * System.out.println(rs.getObject("petname") +" "+ rs.getObject("eventdate")+ " " +rs.getObject("eventtype")+" "+rs.getObject("remark")); * } * * * 防止sql注入攻击 * * String sql = "SELECT * FROM test.event where petname=?;"; * PreparedStatement psql = con.prepareStatement(sql); * psql.setString(1, "xiaohuang"); * rs = psql.executeQuery(); * while(rs.next()) { * System.out.println(rs.getObject("petname") +" "+ rs.getObject("eventdate")+ " " +rs.getObject("eventtype")+" "+rs.getObject("remark")); * } * * * */ } catch (SQLException e) { e.printStackTrace(); }finally { try { rs.close(); st.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
连接池能够对并发连接节省创建资源链接对象的开销 将dbcp2,pool2,logging导入到项目中 基本使用demo如下 public class demo1 { static Statement st = null; static ResultSet rs = null; @SuppressWarnings("resource") public static void main(String[] args) { try { String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"; String username = "root"; String password = "123"; BasicDataSource ds = new BasicDataSource(); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); ds.setInitialSize(10); // 设置连接数 ds.setMaxIdle(5); // 设置最大空闲连接数 ds.setMinIdle(1); // 设置最小空闲连接数 Connection con = ds.getConnection(); st = con.createStatement(); String sql = "insert into test values (7, \"小董\", 30, 'f');"; st.executeUpdate(sql); rs = st.executeQuery("SELECT * FROM test;"); while(rs.next()) { System.out.println(rs.getObject("id") +" "+ rs.getObject("name")+ " " +rs.getObject("age")+" "+rs.getObject("sex")); } } catch (SQLException e) { try { if(st != null) st.close(); if(rs != null) rs.close(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); }finally { } } }
-
- 获取ip
InetAddress id = InetAddress.getLocalHost(); // InetAddress id = InetAddress.getByName("www.baidu.com"); System.out.println(id); // DESKTOP-S2V8PJF/192.168.0.35 System.out.println(id.getHostName()); // DESKTOP-S2V8PJF System.out.println(id.getHostAddress()); // 192.168.0.35
- UDP程序
发送端 public class demo1 { public static void main(String[] args) { try { byte[] sendData = "发送的数据".getBytes(); InetAddress id = InetAddress.getByName("127.0.0.1"); DatagramPacket dp = new DatagramPacket(sendData, sendData.length, id, 9000); DatagramSocket ds = null; try { ds = new DatagramSocket(); try { ds.send(dp); } catch (IOException e) { e.printStackTrace(); } } catch (SocketException e) { e.printStackTrace(); } finally { ds.close(); } } catch (UnknownHostException e) { e.printStackTrace(); } } } 接收端 public class assist { public static void main(String[] args) { DatagramSocket ds = null; DatagramPacket dp = null; byte[] receiveData = new byte[1024]; try { ds = new DatagramSocket(9000); dp = new DatagramPacket(receiveData, receiveData.length); try { ds.receive(dp); System.out.println("由" + dp.getAddress().getHostAddress()+ ":" + dp.getPort() + "发送的数据->" + new String(receiveData, 0, dp.getLength())); } catch (IOException e) { e.printStackTrace(); } } catch (SocketException e) { e.printStackTrace(); }finally { ds.close(); } } }
- TCP程序
客户端 public class demo1 { public static void main(String[] args) { Socket so; OutputStream os; try { so = new Socket("127.0.0.1", 9000); os = so.getOutputStream(); os.write("我是 客户端".getBytes()); // 给服务器发送数据 InputStream in = so.getInputStream(); byte[] data = new byte[1024]; int len = in.read(data); System.out.println(new String(data, 0, len)); // 接受服务器数据 so.close(); } catch (IOException e) { e.printStackTrace(); } } } 服务端 public class assist { public static void main(String[] args) { ServerSocket ss; Socket so; OutputStream os; try { ss = new ServerSocket(9000); so = ss.accept(); InputStream in = so.getInputStream(); byte[] data = new byte[1024]; int len = in.read(data); System.out.println(new String(data, 0, len)); // 接受客户端数据 os = so.getOutputStream(); os.write("知道了".getBytes()); // 发送数据给客户端 os.close(); so.close(); ss.close(); } catch (IOException e) { e.printStackTrace(); } } }