1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java SE基础知识(关键字+运算符+集合+IO+多线程+tcp utb等)

java SE基础知识(关键字+运算符+集合+IO+多线程+tcp utb等)

时间:2023-10-21 05:56:35

相关推荐

java SE基础知识(关键字+运算符+集合+IO+多线程+tcp utb等)

java关键字

byte 8位(-128~127)short 16位(-32768~32767)int 32位(-2^31-1~2 ^31,约 21 亿)long 64位char 16位(0 ~ 2^16-1(65535),可以储存一个中文汉字)float 32位doubie64位boolean true (真)false (假)null (空)class 类package定义包extends继承 import 引包 abstract 抽象 interface 定义接口 implements 实现接口 this. 自身(那个对象调用的他他就是是谁) super. 父类(调取父类的方法及属性)retuen 返回(返回属性或对象,循环及try中会跳出) 访问权限修饰符 private(本类) default(本类+本包的类)protected (本类+本包的类+子类)public (本类,本包的类,子类,非子类及非本包的类)static 静态 final 修饰属性只能赋值一次,定义方法不能被重写finalize GC回收机制(无引用被回收)if()...else 分支判断switch()...case :等值判断 for循环while do循环 do{ 循环体 }while ( 循环条件)break 跳出continue跳出本次try...catch...finally 异常thrownew new ___抛出异常 public abstract void fa(); // 抽象方法 public void fa1(){}// 可重写 可不重写方法 public final void fa2(){}; // 不能被重写的方法System.err.println(sx); //输出红色字体

静态 static 修饰执行顺序

父类的静态块 || 父类的静态成员变量(那个在前就先执行那个)子类静态块 || 子类的静态成员变量父类的普通块 || 父类的普通成员变量父类构造方法子类的普通块 || 子类的普通成员变量父类构造方法

java运算符

~非(~x 的负数 -1),~99 输出 -100, -99 输出 98-负(-x 的负数),-99 输出 99, 99 输出 -99!取非++自增(前++,结果本行改变,后++,结果下行改变)--自减+加-减*乘/除%除(取余)

赋值

= 等于+= +等于(x += 10; 和 x = x+10;结果一致)-= 如: x = x - 10*= 如: x = x * 10/= 如: x = x / 10&= 如: x = x & 10^= 如: x = x ^ 10|= 如: x = x | 10<<=如: x = x << 10>>=如: x = x >> 10x += 10 和 x = x+10 的区别在于 += 是赋值, x = x+10是运算符,运算符默认是 int类型

运算符

&两边为1时,结果为1,否则为0|有一边为1时,结果为1,否则为0~0变1,1变0^不同为1,相同为0

逻辑判断

==等于!=不等于> 大于< 小于>=大于等于<=小于等于&全部 true,判断成立,所有判断都会执行&& 全部 true,判断成立,如果出现了一个false,终止判断表达式|一个为true,判断成立,所有判断都会执行|| 一个为true,判断成立,如果出现的一个 true,终止判断表达式

对象类接口判断

instanceof 左对象,右类或接口。当对象是右面的类(或接口)-或子孙类创建的对象(或实现的接口),该运算符运算结果是true,否则是false。

三元运算符

a>b?true:false 当a大于b的时候,为true(也就是冒号之前的值),否则为false

数学类API

double i = Math.abs(99);绝对值 double i1 = Math.cbrt(8);立方根 double i2 = Math.ceil(9.1); 舍弃小数 加1double i3 = Math.floor(9.9); 舍弃小数double i4 = Math.max(999,666); 取最大值 int i5 = Math.min(999,666); 取最小值double i6 = Math.pow(2,5);x的n次方 double i7 = Math.sqrt(16);开平方;double i8 = Math.PI; 圆周率 π double i9 = Math.E; 自然对数 e

数学类随机数

double x = Math.random(); 随机 >0 - 1< double x1 = x*100; 获得 x*100 的小数int x2 = (int)Math.floor( x *100) + 1;获得 舍弃小数+1 的整数int x3 = (int)( x*100) + 1 ;获得 舍弃小数+1 的整数floor: 返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数

随机数API

Random x = new Random(); intx1 = x.nextInt(); 获得 随机 的整数intx2 = x.nextInt(10); 获得 随机 的指定范围整数boolean x3 = x.nextBoolean(); 获得 随机 false truefloat x4 = x.nextFloat(); 返回 0.0 和 1.0 之间均匀分布的 float 值double x5 = x.nextDouble(); 返回 0.0 和 1.0 之间均匀分布的 double 值Random x = new Random(998) Random(?) 每个数字代表一个随机数对象 intx2 = x.nextInt(10); x.nextInt(10 随机范围

扫描类API

Scanner x = new Scanner(System.in); int x1 = x.nextInt(); 获得 int (数据类型)double x2 = x.nextDouble(); 获得 doubleString x3 = x.nextLine(); 获得 字符串char x1 = x.charAt(0); 获得 第一个字符 (可能异常)

时间类API

Calendar x1 = Calendar.getInstance(); 获得所有日期x1.get(Calendar.YEAR); 年x1.get(Calendar.MONTH)+1;月(+1) x1.get(Calendar.DAY_OF_MONTH); 日x1.get(Calendar.HOUR_OF_DAY) 时x1.get(Calendar.MINUTE); 分x1.get(Calendar.SECOND); 秒x1.get(Calendar.MILLISECOND); 毫秒long x1 = x1.getTimeInMillis();获得日历毫秒数Date xx = new Date();获得当前时间SimpleDateFormat y = new SimpleDateFormat("yyyy/MM/dd E/a HH:mm:ss");String ss = y.format(xx);格式化System.currentTimeMillis(); 获得当前时间的毫秒数,从1970年到现在的毫秒数System.exit(0);退出jvm,后面不执行System.gc(); 调用垃圾回收器String xx = System.getProperty("os.name");

将字符串的类型转化为时间类型

String str = "1999-10-23";SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date date = sdf.parse(str);

//时间递归 当前时间走动

public static void main(String[] args) {fa1();}public static void fa1(){try {Thread.sleep(1000);fa();} catch (InterruptedException e) {e.printStackTrace();}}public static void fa(){Date xx = new Date();SimpleDateFormat y = new SimpleDateFormat("yyyy/MM/dd E/a HH:mm:ss");String ss = y.format(xx);System.out.println(ss);fa1();}

//指定时间到 1970年的毫秒数

SimpleDateFormat xx2 = new SimpleDateFormat("yyyy/MM/dd E/a HH:mm:ss");String x3 = "1995/12/16 星期三/上午 03:12:45"; java.util.Date x4 = xx2.parse(x3); long x5 = x4.getTime();System.out.println(x5);

//程序运行时间计算

public static void test() throws InterruptedException {//执行程序前毫秒数Long time = System.currentTimeMillis();//休眠两秒Thread.sleep(2000);//执行程序后毫秒数Long time1 = System.currentTimeMillis();// /1000 = 秒,/1000/60 = 分, /1000/60/60 = 时Long time2 = (time1 - time)/1000;System.out.println("本次执行程序使用了 "+time2+"秒");}

String

String x = new String();a b c d e f gbyte [] j ={97,98,99,100,101,102,103}; ascii 输出char[] jj = {'a', 'b', 'g', 't','o'};字符 输出String x1 = new String(j);字节字符串String x2 = new String(j,2,5); 截取数组字符串 2索引 3长度 String x3 = new String("qwe"); new 值(地址不同)String x4 = j.trim(); 去掉两边空格int x5 = i.indexOf("s"); 第一次 出现 索引int x5 = i.indexOf("s",3);第一次 出现 索引(指定位置开始)int x6 = j.lastIndexOf("s"); 后往前 第一次 索引int x7 = j.lastIndexOf("s",3); 后往前 第一次 索引(指定位置开始)char x8 = j.charAt(5);指定 索引 字符 char x9 = 输入字符.charAt(j); 获得所有输入字符(遍历j)j.charAt(0)检索字符串中的第一个字符,j.charAt(str.length()-1) 检索最后一个字符String x10 = j.substring(5); 包括开始索引 后面的所有字符String x11 = j.substring(4, 5); (截取字符串)包括开始索引,不包括结束索引byte[] x12 = j.getBytes(); 获得字符串 对应的字节数组(请遍历)j.toUpperCase() 把字符串 转换成 大写j.toLowerCase() 把字符串 转换成 小写j.concat(jj);拼接String.valueOf(x1);把布尔类型 转换成字符串j.endsWith("ld") 判断字符串结尾j.equals("helloworld") 判断两个字符串是否相等,equals比较的是值"helloworld".equals(j) 判断两个字符串是否相等 建议使用 x.contains ("ello") 连续的字符串x.startsWith("hel")字符串开头x .isEmpty() 是否是空串"".isEmpty() 空串

字符串分割

String i = "3000-3999-uuu-999-kkk-2323";String[] ii = i.split(" - ");字符串分割String i1 = i.replace('-','#'); 替换 1 原有 2 换 单引号String i = "3000*3999*uuu*999*kkk*2323";--------------------------------- String[] ii = i.split(" * ");分割String i2 = i.replace("3999","8888");替换 1 -原有 2 -换 双引号

StringBuffer

StringBuffer x1 = new StringBuffer(); StringBuffer x = new StringBuffer(" sweet "); StringBuffer x2 = new StringBuffer(10); 10 容量 不能大于10-----------------------------------------StringBuffer x = x.append("abcd");追加字符串(原地址上增加)x.append (9) .append("a")...... 添加(所有类型)x.length () 获得长度x.capacity() 获得容量x.append (x1) 拼接字符串x.reverse(); 字符串的反转-------------------------------------------------------------------------x.insert(2, true);指定索引插入x.insert(3, "KKKK"); 指定索引插入x.insert(4, new char[]{'a','b','c'});指定索引插入数组x.delete(2,4)删除包含开始索引,不包含结束的索引x.deleteCharAt(5);删除指定的索引的字符,很少用x.delete(3, x.length()); 清空开始索引后面的字符串---------------------------------------------------------------------------int x1 = sb.lastIndexOf("dd"); 向前数,第一次出现的字符串的索引int x = sb.lastIndexOf("dd",2) 指定索引向前数,第一次出现的索引char [] y = {'a','b','c','d'}; x.insert(3, y, 1, 3); 1.起始索引. 2.数组y 3.数组起始索引.4.插入长度x.replace(2, 3, "dddd")1.开始索引 2.替换结束索引 3.替换的字符串String y = new String(); 创建不可变字符串String y1= y +"abc";追加字符串(地址会改变)

反射

Class --> 这个类用于操纵一个类的属性,方法,构造器。Cn.tx.PersonPerson :name,age,addressgetClass() --> obj方法,返回类对象Field类:类属性的抽象Method类:类方法的抽象Constructor类:类构造器的抽象1.通过Class.forName(“类的全路径”);2.通过类的名字打点class,如:Person.class;3.通过调用该类的对象调用getClass()方法Class<?> clazz = Class.forName("java.util.HashMap"); //根据类的全名字符串来获得类的类对象Method[] methods = clazz.getDeclaredMethods(); //获得传递过来的类的所有方法Field[] fields = clazz.getDeclaredFields(); //获得类的所有属性Constructor<?>[] cs = clazz.getDeclaredConstructors(); //获得类的所有的构造器--------------------------------------------------------------------------------Field field = class1.getDeclaredField("address");//获得类对象的一个属性Method method = class1.getDeclaredMethod("getName", new Class[]{}); //获得一个具体的方法 Method method1 = class1.getDeclaredMethod("setName", new Class[]{String.class}); //带参数Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{}); //获得构造器Constructor<?> constructor2 = class1.getDeclaredConstructor(new Class[]{Integer.class, String.class, String.class});

包装类说明

Integer i1 = new Integer(12); 默认: int = 0 ; integer = null Integer i2 = new Integer("90");Integer.MAX_VALUE输出int的最大值 Integer.MIN_VALUE) 输出int的最小值---------------------------------------------------// int ----> Integer 2种方法int xx =10;int Integer x = new Integer(xx);转Integer x1 = Integer.valueOf(xx);Integer转Integer ----> int intxx = x.intValue();--------------------------------------------------String---->Integer(应用最多) 2种方法String xx = "88"; StringInteger x1 = new Integer(xx); 转Integer x2 = Integer.valueOf(xx); Integer---------------------------------------------------Integer ---->String Integer xx = new Integer(9); IntegerString stri6 = i6.toString();转String stri7 = i6 + ""; StringString stri8 = String.valueOf(i6);----------------------------------------------------int i = 9; Integer x = i; 装箱nteger的默认值是nullInteger x1 = new Integer(10);拆箱int i = x1; Integer的默认值是null

异常

Throwable 类是 Java 语言中所有错误或异常的超类。try 异常方法catch 异常处理finally 一定执行1.自定义异常的步骤创建一个异常类继承RuntimeException;2.继承RuntimeException的构造器public class ____Exception extends RuntimeException { }//抛出异常throw new ____Exception("sss");

Object

系统就会认为该类就会直接继承Object类。Object类包含了所有java类的公共属性和方法,这些属性和方法在任何类中均可以直接使用。Object类有一个默认构造方法:public Object() {} //方法体为空,在构造子类实体时,都会先调用这个默认构造方法。Object类常用方法:equals()比较两个类变量所指向的是否为同一对象,是则返回true hashCode() 返回对象的哈希码getClass()获取当前对象所属类的信息,返回Class对象 toString转化成字符串clone() 生成当前对象的一个备份,并返回副本。finalixe() GCwait(); //线程等待notify();//唤醒线程等待,单个notifyAll(); //唤醒使用等待

List --> ArrayList

应用场景: 查询,线程不安全的

Collection 是 list set 的父类List x = new ArrayList() 1.可以允许重复的对象。2.可以插入多个null元素。3.是一个有序容器,保持了每个元素的插入顺序,输出的顺序就是插入的顺序for(String list: arrayList) 增强的for循环--------------------------------------------------------------------------------x.add("a") 添加元素 (可以空,可以字符串,可以数组) x.add(1, "赵六");添加元素 到指定位置x.addAll(1, list); 添加集合 到指定位置x.addAll(list) 添加集合x.removeAll(x1);删除小集合x.remove(1) 删除指定 索引 字符x.remove("宋江") 删除指定 字符x.clear() 清空 元素x.set(0, "小艾");修改x.subList(1, 3) 截取 索引x.element() 获得集合的第一个元素int x1 = x.size()获得集合长度Object x2 = x.get(5);根据索引 来获得 指定元素int x3 = x.indexOf("王五");获得指定 元素的索引int x4 = x.lastIndexOf("王五") 从后第一次 元素索引Object[] x2 = list.toArray(); 把集合转为数组从数组转换过来的list不能添加和删除coll.contains("张三11") 集合中是否包含该元素coll.containsAll(coll1) 大集合是否包含小集合的内容coll.isEmpty() 集合中是否有元素list.push("武松")把元素插入列表的头list.addFirst("白胜"); 把元素插入列表的头list.addLast("吴用"); 把元素插入列表的尾----------------------------------------------------------------------数据添加方法一 --- 集合 直接- new对象Collection<Student> sc1 = new ArrayList<Student>() sc1.add(new Student(2, "刘唐", 1, new Date()));数据添加方法二 --- 创建对象Collection<Student> sc1 = new ArrayList<Student>() Student x = new Student (); x.setLhq(13f);x.setId(3);x.setName("小明");x.setGender(1);x.setBirthday(new Date());cs1.add(cstu); 数据添加方法三 --- 数组GenericTest<Student> gt1 = new GenericTest<Student>();Student[] stuArr = new Student[3];stuArr[0] = new Student(1, "蔡京", 2, new Date());stuArr[1] = new Student(2, "蔡九", 1, new Date());stuArr[2] = new Student(3, "潼关", 2, new Date());gt1.setArr(stuArr);数据添加方法四 --- 迭代器 --暂无

List - LinkedList

应用场景:添加,修改,删除,不是线程安全的

LinkedList ll = new LinkedList();LinkedList 集合ll.add 添加ll.addFirst 前添加ll.addLast 后添加ll.clone() 复制集合ll.element 获得头元素ll.getFirst 第一个元素l.peek()第一个元素ll.poll() 获取并移除第一个元素ll.pop()获取并移除第一个元素ll.push 在最前面添加 一个元素

List - Vector

v.add 添加v.addElement后添加v.capacity 默认长度elementAt(3) 索引的元素 v.insertElementAt("天七", 1) 指定索引位置添加元素//获得集合中的每个元素Enumeration enums= v.elements();while(enums.hasMoreElements()){Object obj = enums.nextElement();/*if("白胜".equals(obj)){v.add("晁盖");/*}System.out.println(obj);}

Set 集合

api 多为同 list

Set<String> set = new HashSet<String>() 无序Set set = new HashSet() 无序Set<String> set = new TreeSet<String>() 自动做自然排序 Set<Person> set = new LinkedHashSet<Person>() 有序* set特点:* 1.无序性* 2.不能重复* 3.允许有null,但是只能有一个* 4.不是同步的(不是线程安全的)A:底层数据结构是哈希表(是一个元素为链表的数组)B:哈希表底层依赖两个方法:hashCode()和equals()首先 hashCode() 比较哈希值是否相同== 继续执行equals()返回true:元素重复了,不添加返回false:直接把元素添加到集合!= 不同:就直接把元素添加到集合------------------------------------------------------------------ 获取set的所以元素Iterator<Person> iter = set.iterator();//set集合不会出现ConcurrentModificationExceptionwhile(iter.hasNext()){//获得下一个元素Person p = iter.next();System.out.println(p);、 if(p.getId() == 1){//删除指定元素set.remove(new Person(3, "诸葛亮", 26));}}System.out.println(set);

ListIterator 迭代器

//定义迭代器,x,coll 是集合ListIterator p = x.listIterator() Iterator iter = coll.iterator();boolean xx = x.containsAll(x1);大集合中是否包含小集合boolean xx = x.equals(x1) 判断大集合是否和小集合相等boolean xx = x.isEmpty() 判断集合中是否有为空boolean xx = x.contains("王5");是否包含某个元素boolean xx = x.hasPrevious(); 是否有前一个元素boolean xx = x.hasNext(); 是否有下一个元素Object x2 = x.next();获得下一个元素 (建议结合while)Object x3 = x.previous();获得上一个元素

取值方法一,上到下

//创建一个集合的迭代器Iterator iterator = coll.iterator();//判断是否存在下一个元素while(iterator.hasNext()){//获得下一个元素Object object = iterator.next();System.out.println(object);}

取值方法二,下到上

//li迭代器的指针已经走到最后了,不能再向下走了,但是可以向前走while(li.hasPrevious()){Object previous = li.previous();System.out.println(previous);}

取值方法三

// 判断 获取下一个元素 (直到获取完)List list = new ArrayList();list.add("s1");list.add("s2");list.add("s3");ListIterator list1 = list.listIterator();while(true){if (list1.hasNext()) {String next = (String) list1.next();System.out.println(next);if(!list1.hasNext()){break;}}}

Map 集合

*---- HashMap和HashTable的区别* 都是键值对集合* HashMap允许有一个空键和多个空值,HashTable不允许有空值和空键* HashMap不是线程安全的,HashTable是线程安全的*map的键不能重复,可以有一个空Map<String, String> map = new Hashtable<String, String>() 有序-按-key 4.3.2.1Map<String, String> map = new HashMap<String,String>() 有序-按-key 4.3.2.1Map<Person, String> map = new TreeMap<Person, String>();有序-按-key 1.2.3.4Map<String, String> map = new LinkedHashMap<String, String>() 添加顺序排列map.put("鼓上蚤", "时迁") 添加map.putAll(map1) 添加集合map.clear() 清空map.remove("1") 根据-key 删除键值对map.get("1")根据-key 获取值map.keySet()拿到Map中所有的键(key)map.containsKey("key3")是否包含指定- keymap.containsValue() 是否包含指定- valuemap.isEmpty()集合是否为空map.entrySet() 获得键值对 --set集合getKey()从 set 中获得-key --键值对set集合getValue() 从 set 中获得-value --键值对set集合map = Collections.synchronizedMap(map) 转线程同步

获取Map 集合中的所有value

for (String coll : (Collection<String>)map.values()){System.out.println("value="+coll);}

获取Map 集合中的所有key ,value

Set<String> set = map.keySet();//遍历keyfor(String key : set){//拿到Map中所有值String value= (String) map.get(key);System.out.println("key="+key+"--value="+value);}//优化代码,同上for(String key : (Set<String>)map.keySet()){System.out.println("key="+key+"--value="+(String) map.get(key));}//s通过entrySet获取所有key,value,for (Map.Entry<String, String> entry : (Set<Map.Entry>)map.entrySet()){System.out.println("key="+ entry.getKey()+"--value="+entry.getValue());}

工具类 Collections,及Arrays

Arrays.binarySearch(arr, val) 二分法查索引 1集合 2 传入值Arrays.sort(arr)数组排序Arrays.toString(arr)数组 tostringArrays.asList(arr) 数组转 listCollections.reverse(list) 集合反转Collections.shuffle(list) 集合打乱Collections.sort(list) 集合排序Collections.synchronizedList(list)变线程安全Collections.sort(? , ?);自写排序 1.集合 2.调用方法pareTo(str1)字符串比较 comparator 继承

Properties 集合+IO(properties配置文件)

说明 :用于写个性化资源文件、如储存 路径-IP 等修改此文件间接修改整个项目的 路径-ip 等Properties prop = new Properties()prop.setProperty() 键值对添加prop.setProperty() 键值对获取prop.keySet() 获得keyprop.getProperty(key)获得value 可以结合打印流-pw.printlnprop.list(pw) 写入 prop.store(pw,null);写入写入数据Properties prop = new Properties();pw = new PrintWriter("d.txt");prop.list(pw);-----------------------------------------读取属性文件到集合中(键值对)-- 多用于自定义配置文件Properties prop = new Properties();fr = new FileReader("src/db.properties");prop.load(fr)------------------------------------------写入 -- 仅限于txtpw = new PrintWriter("d.txt");prop.store(pw, "我的键值对");

properties 配置文件读取方法

public static Integer propExcel1(String exce) {InputStream in = PropExcel.class.getClassLoader().getResourceAsStream("prop.properties");Properties prop = new Properties();Integer rwcn = null;try {prop.load(in);rwcn = Integer.valueOf(prop.getProperty(exce));} catch (Exception e) {e.printStackTrace();}return rwcn;}

properties 配置文件写入方法

public static void propExcelInsert(Integer num,Integer page, Integer hang ,Integer lie, String exceloppn) throws FileNotFoundException {Properties prop = new Properties();///保存属性到b.properties文件FileOutputStream oFile = new FileOutputStream("prop.properties", true);//true追加prop.setProperty("hang"+num, hang+""); //行数prop.setProperty("lie"+num, lie+""); //列数try {prop.store(new OutputStreamWriter(oFile, "utf-8"), exceloppn+"/"+page+"页"+hang+"行"+lie+"列");//prop.store(oFile, "坐标");oFile.close();} catch (IOException e) {e.printStackTrace();}}

File (文件)

File file = new File("C:\\demo.xsd"); 创建对象File file1 = new File("C:/demo.xsd");File file2 = new File("C:/", "demo.xsd");File file = new File("a.txt") 相对路径(当前工程目录下)file.createNewFile() 创建文件 a.txtfile1.mkdirs() 创建文件夹 aafile1.mkdir() 单级目录创建file1.delete() 删除(目录必须空)-可有返回值 booleadfile.getAbsolutePath() 绝对路径file.getPath() 相对路径file.getName() 文件名file.length() 文件大小file.lastModified() 最后修改时间(需格式化时间)File.listRoots()系统的根目录(循环)c\ d\ e\ f\file.listFiles()指定目录下的所有文件(夹)-- E:\java\eclipse vs1file.list()指定目录下的所有文件(夹)名 eclipse vs1file.exists() 判断文件是否存在file.isFile() 判断是否是文件file.isDirectory() 判断是否是文件夹file.isAbsolute() 判断文件是否是绝对路径file.canRead())判断文件是否可读file.canWrite()判断文件是否可写 file.isHidden()判断文件是否是隐藏System.out.println("判断文件是否存在:"+file.exists());System.out.println("判断是否是文件:"+file.isFile());System.out.println("判断是否是文件夹:"+file.isDirectory());System.out.println("判断文件是否是绝对路径:"+file.isAbsolute());System.out.println("判断文件是否可读:"+file.canRead());System.out.println("判断文件是否可写:"+file.canWrite());System.out.println("判断文件是否是隐藏:"+file.isHidden());

IO字符流(文本)

IO流在java中从输入输出角度分类:1.输入流(读) 2.输出流(写)建议使用 高效缓冲 加 数组 来 - 读写IO流在java中从数据的角度来分类:1.字符流 --- 文本,我们能读的懂的都可以认为是字符流。比如:文章,java文件等等Reader: 子类FileReader,BufferedReader-- 输入流 (读)Writer: 子类FileWriter,BufferedWriter-- 输出流 (写)2.字节流 --- 二进制的数据InputStream: 子类FileInputStream -- 输入流(读)OutputStream:子类FileOutputStream-- 输出流 (写)

字符流输出

-------------------字符流输出(写)-会异常----- \r\n 换行---------------------File file = new File("a.txt"); //创建文件 ,true 追加内容fw = new FileWriter(file); //创建输出流对象 fw.write("helloworld"); // 把流指向指定的文件 -可索引指定 -- 开始索引+长度fw.flush(); //释放资源 ,大量数据 - 可批量 %2 fw.close()//关闭流- bw = new BufferedWriter ( fw ) -- 高效缓冲(写) bw.newLine() -- 行分隔 == \r\n//写入文件实列代码fw = new FileWriter("a1.txt"); for(int i = 1;i<999999;i++){if(i%100 != 2){fw.write(i+"=="+"\r\t");fw.flush();}}

字符流输入

-------------------字符流输入(读)-会异常----- \r\n 换行---------------------FileReader fr = new FileReader(a.txt);. //创建出入流对象num= fr.read(); //读取数据 无值 -1 - while循环 (char) ifr.read(chs,0,num) // 数组 chs【1024】 num返回值 fr.close() //关闭输入流,判断非空br = new BufferedReader ( fw ) -- 高效缓冲(读)br.readLine() -- 读取行 - 下一行无数据- null //读取文件实列代码 fr = new FileReader("a.txt");char [] su = new char[2]; int num = fr.read(su);while(num == su.length){num = fr.read(su);System.out.println(new String(su,0,num));}

文件 内容 复制

-----------------------文件 内容 复制-----建议改用 高效缓冲 ------------------------------------------fr = new FileReader("a1.txt");fw = new FileWriter("a.txt");char [] spp = new char[1024];int num = fr.read(spp);while(num == spp.length){num = fr.read(spp);String str = new String(spp,0,num);fw.write(str);fw.flush();}

IO 字节流(二进制文件)

字节流 --- 二进制的数据(视频,图片,mp3)InputStream: 子类FileInputStream -- 输入流 (读)inputOutputStream:子类FileOutputStream -- 输出流 (写)outputin = new BufferedInputStream(new FileInputStream("a.txt"))高效缓冲 读out= new BufferedOutputStream(new FileOutputStream "a.txt")) 高效缓冲 写in = new FileInputStream("a.txt")(读)out = new FileOutputStream("a.txt"); (写)br = str.getBytes- 注意- 写-字符转字节out.write - 写in.read- 读字节转字符流方法 数据 br = new BufferedReader(new InputStreamReader(System.in));字符转字节流方法 bw = new BufferedWriter(new OutputStreamWriter(System.out));// out.newLine()- 写入一行 == \r\n // in.readLine()- 读取一行 --- 下一行无数据- null-----------字节转字符-------------------------------------------------br = new BufferedReader(new InputStreamReader(System.in));wr = new BufferedWriter(new FileWriter("a.txt"));String line = null;while(true){line = br.readLine();if("exit".equals(line)){break;}wr.write(line);wr.newLine();wr.flush();//创建字符流缓冲区对象br = new BufferedReader(new FileReader("a.txt"));//创建字符流缓冲区对象,内部使用字符流转换成字节流的对象OutputStreamWriterwr = new BufferedWriter(new OutputStreamWriter(System.out));String line = null;while((line = br.readLine()) != null){wr.write(line);wr.newLine();wr.flush();}

IO 打印流(直接写入文件)

字符打印流-- 可以打印各种数据-- 自动刷新,不用关闭流(缓冲) -- PrintWriter pw = new PrintWriter(); -- 构造器 建议看 apipw.print pw.println从文件中读取数据并且打印在控制台br = new BufferedReader(new FileReader("a.txt"));pw = new PrintWriter(System.out,true);String line = null;while((line = br.readLine()) != null){pw.println(line);} 复制br = new BufferedReader(new FileReader("a.txt"));pw = new PrintWriter("c.txt");String line = null;while((line = br.readLine()) != null){pw.println(line);}

IO 序列化流(文件保存到本地)

序列化说明:把需要的数据持久化到硬盘上或者数据库上读取多个会出现--边界异常ObjectOutputStreamObjectInputStream序列化对象的类 —— 接口 -- implements Serializable对象类需要设置 uuid 不然无法读取-(版本号不一致)private static final long serialVersionUID = -3050521367627600292L;--------------------------------------------------------写-- 乱码不用管out = new ObjectOutputStream(new FileOutputStream("e.txt"))Person p = new Person(); -- arrayList 写多个p.setName("张三");p.setAge(23);out.writeObject(p);读------------------------------------------------------- in = new ObjectInputStream(new FileInputStream("e.txt"));Object obj = in.readObject();Person p = (Person)obj;System.out.println(p.getName()+ " "+p.getAge());读集合in = new ObjectInputStream(new FileInputStream("e.txt"));Object obj = in.readObject();List<Person> pList = (List<Person>)obj;for(Person p : pList){System.out.println(p);}

IO 流编码

GBK:gb2312做了增强GB18030:对GBK做了增强BIG5:支持繁体Unicode:支持多种国家的语言,这是国际标准。用2个字节来存储。不管是什么字符都用2个字节,会有浪费。UTF-8:支持多种国家的语言,针对不同的字符的范围给出不同的字节表示。0,a,A用一个字符存储中间的范围用二个字节中文就使用3个字节。写入的编码和读取的编码必须要一致,否则会有乱码。byte[] bs = str.getBytes();默认编码byte[] bs1 = str.getBytes("UTF-8");自定义编码String str1 = new String(bs, "GBK"); 解码String str1 = new String(bs, "UTF-8""); 解码//把中国两个字转换成字节然后按照自定义的编码方式存储到文件中pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("f.txt"), "UTF-8"), true);pw.println("中国");读-------br = new BufferedReader(new InputStreamReader(new FileInputStream("f.txt"), "UTF-8"));String str = br.readLine();

多线程

说明:主函数 --------- 线程 垃圾回收机制 ---- 线程 (清理没引用的对象)线程不能同时使用 cpu -- 抢站 cpu(导致并发)新建 -- 准备就绪 -- 运行 -- 阻塞 -- 销毁 ( 生命周期 )多线程 共享数据 --- static实现方法一继承 Thread 重写 runMyThread mt = new MyThread() -- 线程实例对象-类(继承?接口)mt. getName() 获得线程名-thismt .serName() 设置线程名 (也可重写构造器 设置)mt .start() 启动线程( 抢cpu ) -------------------------------------------------------------------实现方法二 Runnbie 接口实现 runMyThread mt = new MyThread()Thread tr = new Thread( mt,? )?-线程名tr .start() -- 启动线程tr.setPriority -- 线程优先(有随机性)tr.join -- 抢先 -独占资源tr.vield-- 回到就绪 - 让出资源 tr.setDaemon( true) -- 守护线程(随主线程结束而结束-main)Thread .currentYherad() .getName()run 中线程名Thread.sleep( 1000 )线程休眠 try共享对象(类).wait ( ) 阻塞(obj 方法)共享对象(类).notify() 唤醒阻塞对象synchronized (obj) 线程锁 obj-同步钥匙(任意类对象)

举例:消费者和生产者

生产者

public class MyThread implements Runnable {static String str = "threadtest1.MyThread"; //锁对象@Overridepublic void run() {//无限循环线程内容while (true) {// 对象锁线程一类中定义的strsynchronized (MyThread.str){try {//线程所执行的方法test();//唤醒 threadtest1.MyThread.str 对象的线程MyThread.str.notify();//休眠Thread.sleep( 2000 );//睡眠 threadtest1.MyThread.strMyThread.str.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}public void test() {System.out.println("线程1 生产了一个苹果,等待购买");}}

消费者:

public class MyThread1 implements Runnable{@Overridepublic void run() {//无限循环线程内容while (true) {// 对象锁线程一类中定义的strsynchronized (MyThread.str){try {//线程所执行的方法test();//唤醒 threadtest1.MyThread.str 对象的线程MyThread.str.notify();//休眠Thread.sleep( 2000 );//睡眠 threadtest1.MyThread.strMyThread.str.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}public void test(){System.out.println("线程2 购买了一个苹果,等待生产");}

}

线程mian

public class Mian{public static void main(String[] args) {Thread th1 = new Thread(new MyThread());Thread th2 = new Thread(new MyThread1());th1.start();th2.start();}}

举例2

4个窗口卖火车票,4个线程(4个线程类都一样)

public class MyThread1 implements Runnable {@Overridepublic void run() {while (true) {//车票没了条出循环if (Mian.num == 0) {System.out.println("车票已卖完");break;}synchronized (Mian.num) {System.out.println("窗口1卖出了第" + --Mian.num + "车票");}}}}

main,大家也可以设置优先级

public class Mian{//锁对象,100张票,4个窗口卖static Integer num = 100;public static void main(String[] args) {//启动 4个线程new Thread(new MyThread1(),"窗口1").start();new Thread(new MyThread2(),"窗口2").start();new Thread(new MyThread3(),"窗口3").start();new Thread(new MyThread4(),"窗口4").start();}

}

模拟多线程处理文件上传

public class Mian {static String mtst = "0";public static void main(String[] args) throws InterruptedException {myThread1 mt1 = new myThread1();Thread th = new Thread(mt1,"线程1");th.join(); //设置优先级th.start();new Thread(new myThread2(), "线程2").start();}//线程1static class myThread1 implements Runnable {@Overridepublic void run() {synchronized (Mian.mtst) {System.out.println("线程1处理:文件上传保存路径相关数据到数据库并返回结果");Map map = new HashMap();map.put("文件名称:", "AA.mp4");map.put("文件路径:", "src/fileMp4/AA。mp4");System.out.println(map.toString());System.out.println("数据保存完成,返回前台,线程2开始执行");}}}//线程2static class myThread2 implements Runnable {@Overridepublic void run() {synchronized (Mian.mtst) {try {System.out.println("--------------------");System.out.println("线程2 开始处理:文件上传到服务器等待线程,文件大,需耗费一定的时间");System.out.println("正在上传中.....");Thread.sleep(2000);System.out.println("文件上传完成");} catch (InterruptedException e) {e.printStackTrace();}}}}}

线程池

newCachedThreadPool

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CachedThreadPooltest {// 自增长线程,可重复使用的线程//创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程//定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。可参考PreloadDataCache。public static void main(String[] args) {ExecutorService cachedThreadPool = Executors.newCachedThreadPool();for (int i = 0; i < 10; i++) {final int index = i;try {Thread.sleep(index * 1000);} catch (InterruptedException e) {e.printStackTrace();}cachedThreadPool.execute(new Runnable() {@Overridepublic void run() {System.out.println(index);}});}}}

newFixedThreadPool

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class fixedThreadPooltest {//并发控制线程//创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。public static void main(String[] args) {ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);for (int i = 0; i < 10; i++) {final int index = i;fixedThreadPool.execute(new Runnable() {@Overridepublic void run() {try {System.out.println(index);Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}}}

newScheduledThreadPool

public class scheduledThreadPool {//定时线程public static void main(String[] args) {ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);/* scheduledThreadPool.schedule(new Runnable() {@Overridepublic void run() {System.out.println("delay 3 seconds");}}, 3, TimeUnit.SECONDS); //表示延时3秒执行*/scheduledThreadPool.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("delay 1 seconds, and excute every 3 seconds");}}, 1, 3, TimeUnit.SECONDS);//表示延时1秒后每3秒执行一次}}

newSingleThreadExecutor

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledThreadPoolExecutor;import java.util.concurrent.TimeUnit;// 指定顺序// 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行public class singleThreadExecutor {public static void main(String[] args) {ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();for (int i = 0; i < 10; i++) {final int index = i;singleThreadExecutor.execute(new Runnable() {@Overridepublic void run() {try {System.out.println(index);Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}}}

线程池创建

/*** Java线程:线程池** @author xiho*/public class Test {public static void main(String[] args) {// 创建一个可重用固定线程数的线程池(5个线程按随机处理)//ExecutorService pool = Executors.newFixedThreadPool(5);//创建单任务线程池(第一个线程处理)//ExecutorService pool = Executors.newSingleThreadExecutor();//可改变尺寸的线程池(5个线程按顺序处理)ExecutorService pool = Executors.newCachedThreadPool();// 创建线程Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();// 将线程放入池中进行执行pool.execute(t1);pool.execute(t2);pool.execute(t3);pool.execute(t4);pool.execute(t5);// 关闭线程池pool.shutdown();}}class MyThread extends Thread {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "正在执行。。。");}}//延时线程class TestScheduledThreadPoolExecutor {public static void main(String[] args) {ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间就触发异常@Overridepublic void run() {//throw new RuntimeException();System.out.println("================");}}, 1000, 5000, TimeUnit.MILLISECONDS);exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的@Overridepublic void run() {System.out.println(System.nanoTime());}}, 1000, 2000, TimeUnit.MILLISECONDS);}}

utp

cmd命令–

-- ipconfig查看 ip-- ping + ip (如:192.168.1.109) 查看两台机器网络是否互通-- netstat -ano 端口InetAddress 类InetAddress ia = InetAddress.getLocalHost(); 本机对象InetAddress ia = InetAddress.getByName("") 根据主机名获取对象ia.getHostAddress() -- ip 获得ia.getHostName();-- 获得主机名下方代码可以多线程--实现 run 抽取ip和端口

服务端

ds = new DatagramSocket(10000);//接收数据的字节数组byte[] bs = new byte[1024];System.err.println("服务器已启动");while (true) {//定义接收的数据包DatagramPacket dp = new DatagramPacket(bs, bs.length);//数据包接收ds.receive(dp);//获得发送端的ipInetAddress ia = dp.getAddress();//接收到的数据-字节byte[] bs1 = dp.getData();//接收到数据的实际长度int len = dp.getLength();//组装数据-字符String data = new String(bs1, 0, len);if("exit".equals(data)){System.err.println("服务端已关闭");break;}System.out.println(ia + "-向你发送了-" + data);

客户端

ds = new DatagramSocket(10001);//控制台输入br = new BufferedReader(new InputStreamReader(System.in));//内容 - 字节数组即可byte [] by = new byte[1024];System.err.println("客户端已启动-- exit关闭服务端-exit1关闭客户端");while (true){//获得一行String st = br.readLine();//退出if("exit1".equals(st)){System.err.println("客户端已关闭");break;}//转字节by = st.getBytes();//发送目的地 -- ip 或 主机名InetAddress ia = InetAddress.getByName("192.16.8.176");DatagramPacket dp = new DatagramPacket(by,by.length,ia,10000);//发送ds.send(dp);

tcp

服务端

//创建服务器套接字ss = new ServerSocket(10000);System.out.println("服务器已启动");//等客户端建立链接s = ss.accept();//获取客户端的ip地址InetAddress ia = s.getInetAddress();//获得通道输入输出流(字节)OutputStream out = s.getOutputStream();//写InputStream in = s.getInputStream();//读br = new BufferedReader(new InputStreamReader(in));String line = null;while ((line = br.readLine()) != null) {System.out.println(ia + "=" + line);}

客户端

//创建套接字对象s = new Socket("192.168.1.36", 10000);//获得输出流(写)OutputStream out = s.getOutputStream();br = new BufferedReader(new InputStreamReader(System.in));//字符转字节流writer = new BufferedWriter(new OutputStreamWriter(out));String line = null;while ((line = br.readLine()) != null){writer.write(line);writer.newLine();writer.flush();}

多线程+utp

客服端+服务端线程合并类

import java.io.*;import .InetAddress;import .ServerSocket;import .Socket;public class Thread_utb implements Runnable {int jsPort, fsPort;String ip;// ===================================客户端+服务端-合并线程// 当前线程类,启动服务器和客服端@Overridepublic void run() {FWDThread.port = jsPort; //设置消息接收的端口KFDThread.ip = ip; //设置发送消息的 ip本机可以使用localhost 和 127.0.0.1KFDThread.port = fsPort; //设置发送消息给指定人的端口//启动线程new Thread(new FWDThread()).start();new Thread(new KFDThread()).start();}public Thread_utb(int jsPort, int fsPort, String ip) {this.jsPort = jsPort;this.fsPort = fsPort;this.ip = ip;}public Thread_utb() {}}// ===================================服务端线程//服务端接收消息 : 指定接收消息的端口class FWDThread implements Runnable {//定义发送消息的端口static int port;@Overridepublic void run() {BufferedReader br;ServerSocket ss;Socket s;//等客户端建立链接try {//创建服务器套接字ss = new ServerSocket(port);System.out.println("服务器已启动");s = ss.accept();//获取客户端的ip地址InetAddress ia = s.getInetAddress();//获得通道输入输出流(字节)//OutputStream out = s.getOutputStream();//写InputStream in = s.getInputStream();//读br = new BufferedReader(new InputStreamReader(in));String line = null;//接收消息并输出while ((line = br.readLine()) != null) {System.out.println(ia + "=" + line);}} catch (IOException e) {e.printStackTrace();}}}// ===================================客户端线程//客服端发送消息 : 指定ip + 端口class KFDThread implements Runnable {//定义发送消息的端口static int port;//定义要发到消息的 ipstatic String ip;@Overridepublic void run() {BufferedReader br;Socket s;BufferedWriter writer;//创建套接字对象try {s = new Socket(ip, port);System.out.println("对方在线,网络连接成功");//获得输出流(写)OutputStream out = s.getOutputStream();br = new BufferedReader(new InputStreamReader(System.in));//字符转字节流writer = new BufferedWriter(new OutputStreamWriter(out));String line = null;//发送控制台打印的消息while ((line = br.readLine()) != null) {writer.write(line);writer.newLine();writer.flush();}} catch (IOException e) {//e.printStackTrace();System.out.println("对方不在线,5秒后再次尝试连接");try {Thread.sleep(5000);} catch (InterruptedException e1) {e1.printStackTrace();}this.run();}}}

线程启动

// 用户1、启动线程 给 10001发信息// 参数1,接收消息的端口// 参数2,对方接收消息的端口// 参数3,对方接收消息的ippublic class MainThread{public static void main(String[] args) {new Thread(new Thread_utb(10000, 10001, "127.0.0.1")).start();}}// 用户2、启动线程 给 10000发信息class MainThread2{public static void main(String[] args) {new Thread(new Thread_utb(10001, 10000, "127.0.0.1")).start();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。