Java常用对象
一、String与StringBuffer, StringBuild
String在java编程中广泛应用,其低层采用final修饰的char[]数组完成。所以String的值是不可变的,每次对String的操作都会生成新的String对象,造成内存浪费
StringBuffer和StringBuilder,他们两都继承了AbstractStringBuilder抽象类,他们的底层都是可变的字符数组,所以在进行频繁的字符串操作时,建议使用StringBuffer和StringBuilder来进行操作。
StringBuilder,StringBuffer字符串拼接
StringBuilder:非线程安全 ---->使用于单线程
StringBuffer:支持线程安全 ---> 使用于多线程。
实例:
String s1 = "Monday";
String s2 = new String("Monday");
if (s1 == s2) {
System.out.println("s1 == s2");
}
else {
System.out.println("s1 != s2");
}
if (s1.equals(s2)) {
System.out.println("s1 equals s2");
}
else {
System.out.println("s1 not equals s2");
}
String字符串的常用函数:字符串的所有函数都静态函数
asdf==asfas
SN(序号) | 方法描述 |
---|---|
1 | char charAt(int index) 返回指定索引处的 char 值。 ”abc“.charAt(1) |
2 | int compareTo(Object o) 把这个字符串和另一个对象比较。 |
3 | int compareTo(String anotherString) 按字典顺序比较两个字符串。 |
4 | int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写。 |
5 | String concat(String str) 将指定字符串连接到此字符串的结尾。 |
6 | boolean contentEquals(StringBuffer sb) 当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。 |
7 | [static String copyValueOf(char] data) 返回指定数组中表示该字符序列的 String。 |
8 | [static String copyValueOf(char] data, int offset, int count) 返回指定数组中表示该字符序列的 String。 |
9 | boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结束。 |
10 | boolean equals(Object anObject) 将此字符串与指定的对象比较。 |
11 | boolean equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写。 |
12 | [byte] getBytes() 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
13 | [byte] getBytes(String charsetName) 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
14 | [void getChars(int srcBegin, int srcEnd, char] dst, int dstBegin) 将字符从此字符串复制到目标字符数组。 |
15 | int hashCode() 返回此字符串的哈希码。 |
16 | int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。 |
17 | int indexOf(int ch, int fromIndex) 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 |
18 | int indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引。 |
19 | int indexOf(String str, int fromIndex) 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 |
20 | String intern() 返回字符串对象的规范化表示形式。 |
21 | int lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。 |
22 | int lastIndexOf(int ch, int fromIndex) 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 |
23 | int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。 |
24 | int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 |
25 | int length() 返回此字符串的长度。 |
26 | boolean matches(String regex) 告知此字符串是否匹配给定的正则表达式。 |
27 | boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。 |
28 | boolean regionMatches(int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。 |
29 | String replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 |
30 | String replaceAll(String regex, String replacement) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 |
31 | String replaceFirst(String regex, String replacement) 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 |
32 | [String] split(String regex) 根据给定正则表达式的匹配拆分此字符串。 |
33 | [String] split(String regex, int limit) 根据匹配给定的正则表达式来拆分此字符串。 |
34 | boolean startsWith(String prefix) 测试此字符串是否以指定的前缀开始。 |
35 | boolean startsWith(String prefix, int toffset) 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。 |
36 | CharSequence subSequence(int beginIndex, int endIndex) 返回一个新的字符序列,它是此序列的一个子序列。 |
37 | String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。 |
38 | String substring(int beginIndex, int endIndex) 返回一个新字符串,它是此字符串的一个子字符串。 |
39 | [char] toCharArray() 将此字符串转换为一个新的字符数组。 |
40 | String toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。 |
41 | String toLowerCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。 |
42 | String toString() 返回此对象本身(它已经是一个字符串!)。 |
43 | String toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。 |
44 | String toUpperCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。 |
45 | String trim() 返回字符串的副本,忽略前导空白和尾部空白。 |
46 | static String valueOf(primitive data type x) 返回给定data type类型x参数的字符串表示形式。 |
47 | contains(CharSequence chars) 判断是否包含指定的字符系列。 |
48 | isEmpty() 判断字符串是否为空。 |
二、正则表达式
1、String类的matches函数可以完成正则验证
String a = "abc";
String regex = "abc";
boolean isA = a.matches(regex);
System.out.println(isA);
2、Pattern 类:
pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,
你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一
个参数。
String a = "abcdasdf";
String regex = "\\w+";
boolean isA = Pattern.matches(regex, a);
System.out.println(isA);
System.out.println(a.matches(regex));
3、常用正则表达式语法格式:
System.out.print("\\"); // 输出为 \
System.out.print("\\\\"); // 输出为 \\
4、正则表达式实例:
邮箱校验
String regex = "^\\w+@\\w+\\.+([a-zA-Z]{2,})$";
String email = "345asfd@qq.com";
//Pattern regex = Pattern.compile(check);
boolean isEmail = Pattern.matches(regex, email);
System.out.println(isEmail);
字符 | 说明 |
---|---|
\ | 将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如, n匹配字符 n。\n 匹配换行符。序列 \\ 匹配 \ ,\( 匹配 (。 |
^ | 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与"\n"或"\r"之后的位置匹配。 |
$ | 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与"\n"或"\r"之前的位置匹配。 |
* | 零次或多次匹配前面的字符或子表达式。例如,zo* 匹配"z"和"zoo"。* 等效于 {0,}。 |
+ | 一次或多次匹配前面的字符或子表达式。例如,"zo+"与"zo"和"zoo"匹配,但与"z"不匹配。+ 等效于 {1,}。 |
? | 零次或一次匹配前面的字符或子表达式。例如,"do(es)?“匹配"do"或"does"中的"do”。? 等效于 {0,1}。 |
{n} | n 是非负整数。正好匹配 n 次。例如,"o{2}"与"Bob"中的"o"不匹配,但与"food"中的两个"o"匹配。 |
{n,} | n 是非负整数。至少匹配 n 次。例如,"o{2,}“不匹配"Bob"中的"o”,而匹配"foooood"中的所有 o。"o{1,}“等效于"o+”。"o{0,}“等效于"o*”。 |
{n,m} | m 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,"o{1,3}"匹配"fooooood"中的头三个 o。‘o{0,1}’ 等效于 ‘o?’。注意:您不能将空格插入逗号和数字之间。 |
? | 当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是"非贪心的"。"非贪心的"模式匹配搜索到的、尽可能短的字符串,而默认的"贪心的"模式匹配搜索到的、尽可能长的字符串。例如,在字符串"oooo"中,"o+?“只匹配单个"o”,而"o+“匹配所有"o”。 |
. | 匹配除"\r\n"之外的任何单个字符。若要匹配包括"\r\n"在内的任意字符,请使用诸如"[\s\S]"之类的模式。 |
x|y | 匹配 x 或 y。例如,‘z|food’ 匹配"z"或"food"。‘(z|f)ood’ 匹配"zood"或"food"。 |
[xyz] | 字符集。匹配包含的任一字符。例如,"[abc]“匹配"plain"中的"a”。 |
[^xyz] | 反向字符集。匹配未包含的任何字符。例如,"[^abc]“匹配"plain"中"p”,“l”,“i”,“n”。 |
[a-z] | 字符范围。匹配指定范围内的任何字符。例如,"[a-z]"匹配"a"到"z"范围内的任何小写字母。 |
[^a-z] | 反向范围字符。匹配不在指定的范围内的任何字符。例如,"[^a-z]"匹配任何不在"a"到"z"范围内的任何字符。 |
\b | 匹配一个字边界,即字与空格间的位置。例如,“er\b"匹配"never"中的"er”,但不匹配"verb"中的"er"。 |
\B | 非字边界匹配。“er\B"匹配"verb"中的"er”,但不匹配"never"中的"er"。 |
\d | 数字字符匹配。等效于 [0-9]。 |
\D | 非数字字符匹配。等效于 [^0-9]。 |
\f | 换页符匹配。等效于 \x0c 和 \cL。 |
\n | 换行符匹配。等效于 \x0a 和 \cJ。 |
\v | 垂直制表符匹配。与 \x0b 和 \cK 等效。 |
\w | 匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。 |
\W | 与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。 |
afa1123s_fsadf@qq.com
String str = "^\\w+@\\w+.\\w+$"
三、Java时间处理
1900年1月1日 08:00:00
字符串与时间类型的转换;时间格式; 时间戳
java.util.Date:
// 创建对象
Date d = new Date();
long time = d.getTime();
System.out.println(time);
System.out.println("d:" + d);
//当前时间戳
//System.currentTimeMillis()
// 设置时间
d.setTime(1000);
System.out.println("d:" + d);
SimpleDateFormat:格式化时间
Date dd = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String s = sdf.format(dd);
System.out.println(s);
SimpleDateFormat:解析字符串为时间
String str = "2008-08-08 12:12:12";
//在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(str);
System.out.println(dd);
SimpleDateFormat时间格式:
hh:12小时制 HH:24小时制
把时间戳1642060370158转换成时间对象,并获取年-月-日 时:分:秒
Date setTime(1642060370158)
Calendar:
Calendar c1 = Calendar.getInstance();
// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;
// 获得日期
int date = c1.get(Calendar.DATE);
// 获得小时
int hour = c1.get(Calendar.HOUR_OF_DAY);
// 获得分钟
int minute = c1.get(Calendar.MINUTE);
// 获得秒
int second = c1.get(Calendar.SECOND);
// 获得星期几(注意(这个与Date类是不同的):1代表星期日、2代表星期1、3代表星期二,以此类推)
int day = c1.get(Calendar.DAY_OF_WEEK);
Calendar转换成Date:
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime;
//把c1对象的日期加上10,也就是c1也就表示为10天后的日期
calendar.add(Calendar.DATE, 10);
把c1对象的日期减去10,也就是c1也就表示为10天前的日期
calendar.add(Calendar.DATE, -10);
Date 转换成 Calendar:
Date date = new Date();
Calendar calendar = Calsendar.getInstance();
calendar.setTime(date );
24 60 60 1000
四、Number与Math对象
所有的包装类(Integer、Long、Byte、Double、Float、Short)都是抽象类 Number 的子类。
Java 的 Math 包含了用于执行基本数学运算的属性和方法,如初等指数、对数、平方根和三角函数。
序号 | 方法与描述 |
---|---|
1 | xxxValue() 将 Number 对象转换为xxx数据类型的值并返回。 |
2 | compareTo() 将number对象与参数比较。 |
3 | equals() 判断number对象是否与参数相等。 |
4 | valueOf() 返回一个 Number 对象指定的内置数据类型 |
5 | toString() 以字符串形式返回值。 |
6 | parseInt() 将字符串解析为int类型。 |
7 | abs() 返回参数的绝对值。 |
8 | ceil() 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。 |
9 | floor() 返回小于等于(<=)给定参数的最大整数 。 |
10 | rint() 返回与参数最接近的整数。返回类型为double。 |
11 | round() 它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。 |
12 | min() 返回两个参数中的最小值。 |
13 | max() 返回两个参数中的最大值。 |
14 | exp() 返回自然数底数e的参数次方。 |
15 | log() 返回参数的自然数底数的对数值。 |
16 | pow() 返回第一个参数的第二个参数次方。 |
17 | sqrt() 求参数的算术平方根。 |
18 | sin() 求指定double类型参数的正弦值。 |
19 | cos() 求指定double类型参数的余弦值。 |
20 | tan() 求指定double类型参数的正切值。 |
21 | asin() 求指定double类型参数的反正弦值。 |
22 | acos() 求指定double类型参数的反余弦值。 |
23 | atan() 求指定double类型参数的反正切值。 |
24 | atan2() 将笛卡尔坐标转换为极坐标,并返回极坐标的角度值。 |
25 | toDegrees() 将参数转化为角度。 |
26 | toRadians() 将角度转换为弧度。 |
27 | random() 返回一个随机数。 |
Math 的 floor,round 和 ceil 方法实例比较
参数 | Math.floor | Math.round | Math.ceil |
---|---|---|---|
1.4 | 1 | 1 | 2 |
1.5 | 1 | 2 | 2 |
1.6 | 1 | 2 | 2 |
-1.4 | -2 | -1 | -1 |
-1.5 | -2 | -1 | -1 |
-1.6 | -2 | -2 | -1 |
实例:产生1-10的随机整数 伪随机
int m = (int) (Math.random()*10 + 1);
System.out.println(m);
五、泛型
1、泛型只在编译阶段有效。看下面的代码:
List<String> strings = new ArrayList<String>();
List<Integer> integers = new ArrayList<Integer>();
Class stringsClass = strings.getClass();
Class integersClass = integers.getClass();
if(integersClass.equals(stringsClass)){
System.out.println("泛型测试:泛型相同");
}
泛型类型在逻辑上看以看成是多个不同的类型,实际上都是相同的基本类型
泛型的使用
泛型有三种使用方式,分别为:泛型类、泛型接口、泛型方法
泛型类的最基本写法(这么看可能会有点晕,会在下面的例子中详解):
class 类名称 <泛型标识:可以随便写任意标识号,标识指定的泛型的类型>{
private 泛型标识 /*(成员变量类型)*/ var;
.....
}
}
一: 定义一个普通的泛型类:
//此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
//在实例化泛型类时,必须指定T的具体类型
public class Persion<T>{
//key这个成员变量的类型为T,T的类型由外部指定
private T key;
public Persion(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
this.key = key;
}
public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
return key;
}
}
//泛型的类型参数只能是类类型(包括自定义类),不能是简单类型
Persion<String> plan = new Persion<String>("F22");
Persion<Integer> inte = new Persion<Integer>(12345);
System.out.println(plan.getKey());
System.out.println(inte.getKey());
定义的泛型类,就一定要传入泛型类型实参么?并不是这样,在使用泛型的时候如果传入泛型实参,
则会根据传入的泛型实参做相应的限制,此时泛型才会起到本应起到的限制作用。如果不传入泛型
类型实参的话,在泛型类中使用泛型的方法或成员变量定义的类型可以为任何的类型。
二、泛型接口
泛型接口与泛型类的定义及使用基本相同。
//定义一个泛型接口
public interface Human<T> {
T getHuman();
}
public class ZhangSan implements Human<String> {
@Override
public String getHuman() {
return "张三";
}
}
Human human = new ZhangSan();
System.out.println(human.getHuman());
三、普通类泛型类与泛型接口结合使用
public interface Human<T> {
T getHuman();
}
public class ZhangSan<T> implements Human<T> {
private T t;
public ZhangSan(T t){
this.t = t;
}
@Override
public T getHuman() {
return t;
}
}
Human human = new ZhangSan("张三");
System.out.println(human.getHuman());
4、方法泛型
public class Cat {
private int id;
private String name;
public Cat() {
}
public Cat(int id, String name) {
this.id = id;
this.name = name;
}
//省略get/set方法
}
public class Persion<T> {
//key这个成员变量的类型为T,T的类型由外部指定
private T key;
//泛型构造方法形参key的类型也为T,T的类型由外部指定
public Persion(T key) {
this.key = key;
}
//泛型方法getKey的返回值类型为T,T的类型由外部指定
public T getKey(){
return key;
}
//方法泛型的格式
//<T>位于返回值前
public <T> void getOtherKey(T[] array, T e){
array[0] = e;
}
}
Cat[] cats = new Cat[1];
plan.getOtherKey(cats, new Cat(2,"mimi"));
System.out.println(cats[0].getName());
泛型的上限,下限,通配符
六、集合类框架
数据结构:数据结构是计算机存储、组织数据的方式
常用的数据结构:数组,堆,栈,队列,链表,树,图,散列表
数据结构种常用的算法:
(1)检索。检索就是在数据结构里查找满足一定条件的节点。一般是给定一个某字段的值,找具有该字段值的节点。
(2)插入。往数据结构中增加新的节点。
(3)删除。把指定的结点从数据结构中去掉。
(4)更新。改变指定节点的一个或多个字段的值。
(5)排序。把节点按某种指定的顺序重新排列。例如递增或递减。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IZD3RWAo-1670987581899)(raw/c15.png)]
主要内容:
1、集合类框架介绍
2、Collection接口及主要方法
3、Iterable接口
4、List接口
5、Set接口
6、Map接口
7、Collections类
8、数组与集合
List转换为Array可以这样处理:
ArrayList<String> list=new ArrayList<String>();
String[] strings = new String[list.size()];
list.toArray(strings);
反过来,如果要将数组转成List怎么办呢?如下:
String[] s = {"a","b","c"};
List list = java.util.Arrays.asList(s);
9、集合排序
//集合反转排序
方式1、list.sort(Comparator.comparing(类名::get属性).reversed());
方式2、Collections.reverse(strings);
自定义排序与复合排序:
方式1:Collections.sort(list集合, new Comparator<类名>() {
//o1, o2:是集合的相邻两项,其中o1是前一项,o2是后一项
//返回值大于0:降序, 返回值小于0:升序
@Override
public int compare(Score o1, Score o2) {
return 0
}
});
方式2:集合对象.sort((Score o1, Score o2)-> {
return 0
});
方式3:集合对象.sort(Comparator.comparing(类名::get属性));
方式4:scoreList.sort(new Comparator<Score>() {
@Override
public int compare(Score o1, Score o2) {
return 0;
}
});
10、常见的高级集合对象(线程安全的集合对象)
CopyOnWriteArrayList
CopyOnWriteArraySet
Collections.synchronizedList
Collections.synchronizedMap(new Hashtable<String,Object>());
Collections.synchronizedMap()
ConcurrentHashMap
11、HashMap实现原理
jdk1.8最重要的就是引入了红黑树的设计,当hash表的单一链表长度超过 8 个的时候,链表结构就会转为红黑树结构。
12、Collectons:集合操作类。
sort(Comparator com):集合排序
Comparator排序工具类:重写compare()
13、Comparable与Comparator区别?
14、Collectons与Collecton的区别?
15、集合的嵌套?
List集合嵌套Map, Map嵌套List
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8XVxOgVj-1670987581900)(raw/c13.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-viTmyfFX-1670987581900)(raw/c12.png)]
七、FastJSON字符串
Jackson, fastJSON, Gson
{"name":"Yang", "id":"01"}:JSON对象
["aaa", "bbb"]:JSON数组
[{"name":"Yang", "id":"01"},{"name":"Yang", "id":"01"}]
JSONObject:json对象
JSONObject.parseObject(String jsonStr) -> json字符串转换成JSONObject
JSONArray:json数组
JSONArray.parseArray(String jsonStr)->json字符串转换成JSONArray
JSON: 对字符串操作的类
1、Java对象转JSON字符串:JSON.toJSONString(Object obj)
2、字符串转JSONObject对象:JSONObject.parseObject(String jsonStr)
3、字符串转JSONArray数组:JSONArray.parseArray(String sonStr)
4、把JSON字符串转换成Java对象
/**字符串转JavaBean:
* JSON.parseObject(str, 类名.class)*/
private static void strToJavaObject(){
String str = "{\"className\":\"肖扬组\",\"stuAddress\":\"成都\",\"stuBirthday\":881856000000,\"stuId\":1,\"stuName\":\"Yang\"}";
Student stu = JSON.parseObject(str, Student.class);
System.out.println(stu.getClassName() + "---" + stu.getStuId());
}
/**Java对象装JSON字符串:
* JSON.toJSONString(Object obj)
* */
private static void mapToJsonStr(){
Map<String, String> map = new HashMap<>();
map.put("id", "01");
map.put("name", "F22");
map.put("country", "USA");
/**Java对象装JSON字符串:JSON.toJSONString(Object obj)*/
String jsonStr = JSON.toJSONString(map);
System.out.println(jsonStr);
/**JSONObject.parseObject(jsonStr):字符串转JSONObject对象*/
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
System.out.println(jsonObject.get("id"));
}
private static void listToJsonStr(){
List<String> list = new ArrayList<>();
list.add("F22");
list.add("F35");
/**Java对象装JSON字符串:JSON.toJSONString(Object obj)*/
String jsonStr = JSON.toJSONString(list);
System.out.println(jsonStr);
/**JSONArray.parseArray(jsonStr):字符串转JSONArray对象*/
JSONArray jsonArray = JSONArray.parseArray(jsonStr);
System.out.println(jsonArray.size());
}
private static void listMapToJsonStr(){
Map<String, String> map = new HashMap<>();
map.put("id", "01");
map.put("name", "F22");
map.put("country", "USA");
Map<String, String> map1 = new HashMap<>();
map1.put("id", "02");
map1.put("name", "F35");
map1.put("country", "USA");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map);
list.add(map1);
String jsonStr = JSON.toJSONString(list);
System.out.println(jsonStr);
}
private static void listStudentToJsonStr() throws ParseException {
Student yang = new Student(1, "Yang", new SimpleDateFormat("yyyy-MM-dd").parse("1997-12-12"), "成都", "肖扬组");
Student liu = new Student(2, "Liu", new SimpleDateFormat("yyyy-MM-dd").parse("1997-12-12"), "成都", "肖扬组");
Student zhang = new Student(3, "Zhang", new SimpleDateFormat("yyyy-MM-dd").parse("1997-12-12"), "成都", "肖扬组");
Student li = new Student();
li.setStuId(4);
List<Student> students = new ArrayList<Student>();
students.add(yang);
students.add(liu);
students.add(zhang);
students.add(li);
String jsonStr = JSON.toJSONString(students);
System.out.println(jsonStr);
JSONArray jsonArray = JSONArray.parseArray(jsonStr);
jsonArray.forEach((item)->{
JSONObject jsonObject = JSONObject.parseObject(item.toString());
System.out.print(jsonObject.get("stuId") + "--" + jsonObject.get("stuName") + "--" + jsonObject.get("className") + "---");
System.out.println();
});
}
八、File类对现象
Java文件类以抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等
File类的构造方法:
File(String pathname): 通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。
File(String parent, String child) :根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
File(File parent, String child):通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。
创建File对象成功后,可以使用以下列表中的方法操作文件。
序号 | 方法描述 |
---|---|
1 | public String getName() 返回由此抽象路径名表示的文件或目录的名称。 |
2 | public String getParent()****、 返回此抽象路径名的父路径名的路径名字符串,如果此路径名没有指定父目录,则返回 null 。 |
3 | public File getParentFile() 返回此抽象路径名的父路径名的抽象路径名,如果此路径名没有指定父目录,则返回 null 。 |
4 | public String getPath() 将此抽象路径名转换为一个路径名字符串。 |
5 | public boolean isAbsolute() 测试此抽象路径名是否为绝对路径名。 |
6 | public String getAbsolutePath() 返回抽象路径名的绝对路径名字符串。 |
7 | public boolean canRead() 测试应用程序是否可以读取此抽象路径名表示的文件。 |
8 | public boolean canWrite() 测试应用程序是否可以修改此抽象路径名表示的文件。 |
9 | public boolean exists() 测试此抽象路径名表示的文件或目录是否存在。 |
10 | public boolean isDirectory() 测试此抽象路径名表示的文件是否是一个目录。 |
11 | public boolean isFile() 测试此抽象路径名表示的文件是否是一个标准文件。 |
12 | public long lastModified() 返回此抽象路径名表示的文件最后一次被修改的时间。 |
13 | public long length() 返回由此抽象路径名表示的文件的长度。 |
14 | public boolean createNewFile() throws IOException 当且仅当不存在具有此抽象路径名指定的名称的文件时,原子地创建由此抽象路径名指定的一个新的空文件。 |
15 | public boolean delete() 删除此抽象路径名表示的文件或目录。 |
16 | public void deleteOnExit() 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。 |
17 | public String[] list() 返回由此抽象路径名所表示的目录中的文件和目录的名称所组成字符串数组。 |
18 | public String[] list(FilenameFilter filter) 返回由包含在目录中的文件和目录的名称所组成的字符串数组,这一目录是通过满足指定过滤器的抽象路径名来表示的。 |
19 | public File[] listFiles() 返回一个抽象路径名数组,这些路径名表示此抽象路径名所表示目录中的文件。 |
20 | public File[] listFiles(FileFilter filter) 返回表示此抽象路径名所表示目录中的文件和目录的抽象路径名数组,这些路径名满足特定过滤器。 |
21 | public boolean mkdir() 创建此抽象路径名指定的目录。 |
22 | public boolean mkdirs() 创建此抽象路径名指定的目录,包括创建必需但不存在的父目录。 |
23 | public boolean renameTo(File dest) 重新命名此抽象路径名表示的文件。 |
24 | public boolean setLastModified(long time) 设置由此抽象路径名所指定的文件或目录的最后一次修改时间。 |
25 | public boolean setReadOnly() 标记此抽象路径名指定的文件或目录,以便只可对其进行读操作。 |
26 | public static File createTempFile(String prefix, String suffix, File directory) throws IOException 在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。 |
27 | public static File createTempFile(String prefix, String suffix) throws IOException 在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。 |
28 | public int compareTo(File pathname) 按字母顺序比较两个抽象路径名。 |
29 | public int compareTo(Object o) 按字母顺序比较抽象路径名与给定对象。 |
30 | public boolean equals(Object obj) 测试此抽象路径名与给定对象是否相等。 |
31 | public String toString() 返回此抽象路径名的路径名字符串。 |
File实例:
File file = new File("D:\\JavaSe10");
String fileName = file.getName();
System.out.println("文件名:" + fileName);
boolean isDir = file.isDirectory();
System.out.println("是否目录:" + isDir);
String parentFile = file.getParent();
System.out.println("父目录:" + parentFile);
/**list():子文件名称*/
String[] childList = file.list();
for (String childFileName:childList) {
System.out.print(childFileName + "--");
}
System.out.println();
/**mkdirs():创建目录结构; mkdir():创建单个目录*/
File createFile = new File("D:\\FileTest\\One");
boolean isMakeDir = createFile.mkdirs();
System.out.println("是否创建文件目录:" + isMakeDir);
/**createNewFile:创建文件*/
File createFile1 = new File("D:\\FileTest\\One\\text.txt");
try{
createFile1.createNewFile();
} catch (Exception e){
e.printStackTrace();
}
/**删除文件*/
createFile1.deleteOnExit();
时间戳转时间?
把时间戳1642060370158转换成时间对象,并获取年-月-日 时:分:秒
Date newDate = new Date();
newDate.setTime(1642060370158l);
//时间对象的格式化
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//时间字符串
String timeStr = sdf1.format(newDate);
System.out.println(timeStr);
//Calendar时间对象
Calendar calendar = Calendar.getInstance();
//Date转Calendar时间对象
calendar.setTime(newDate);
计数2002-10-10 00:00:00至今有多少天?
第一步:计算2002-10-10 00:00:00的毫秒数
第二步:计算当前的毫秒数
第三步:(当前的毫秒数 - 2002-10-10 00:00:0的毫秒数)/ (24 * 60 * 60 * 1000) = 天数
计算在25小时10分23秒后的时间点?
第一步:获取当前时间戳
第二步:获取25小时10分23秒的毫秒数
第三步:当前时间戳 + 25小时10分23秒的毫秒数
第四步:把第三步的时间戳转换成时间
字符串转时间类型?
把字符串"2022-01-03 16:04:14"转换成Data时间对象
12:25:35时,秒针与时针的夹角
课后作业:
String,StringBuffer, StringBuilder的区别?
String str = "i"与String str = new String("i")一样吗?
String类常用的方法及作用,请写出代码实例?
简述Java集合?
List,Map,Set三个接口存取数据元素时,各有什么特点?请写出代码实例?
Set里的元素为什么不能重复,使用==还是equale()?
简述ArrayList与LinkedList的区别?
简述ArrayList,Vector, LinkedList存储性能?
简述HashMap与HashTable的区别?
HashMap的实现原理(链表与红黑树)?
预习:
1、Map集合的遍历方式
2、预习集合排序及自定义排序
3、集合与数组的转换
4、预习JSON字符串(JSON字符串与ava对象的相互转换) 以fastJSON为实例
5、预习文件流(字节流、字符流)
至今有多少天?
第一步:计算2002-10-10 00:00:00的毫秒数
第二步:计算当前的毫秒数
第三步:(当前的毫秒数 - 2002-10-10 00:00:0的毫秒数)/ (24 * 60 * 60 * 1000) = 天数
计算在25小时10分23秒后的时间点?
第一步:获取当前时间戳
第二步:获取25小时10分23秒的毫秒数
第三步:当前时间戳 + 25小时10分23秒的毫秒数
第四步:把第三步的时间戳转换成时间
字符串转时间类型?
把字符串"2022-01-03 16:04:14"转换成Data时间对象
12:25:35时,秒针与时针的夹角
#### 课后作业:
String,StringBuffer, StringBuilder的区别?
String str = "i"与String str = new String(“i”)一样吗?
String类常用的方法及作用,请写出代码实例?
简述Java集合?
List,Map,Set三个接口存取数据元素时,各有什么特点?请写出代码实例?
Set里的元素为什么不能重复,使用==还是equale()?
简述ArrayList与LinkedList的区别?
简述ArrayList,Vector, LinkedList存储性能?
简述HashMap与HashTable的区别?
HashMap的实现原理(链表与红黑树)?
预习:
1、Map集合的遍历方式
2、预习集合排序及自定义排序
3、集合与数组的转换
4、预习JSON字符串(JSON字符串与ava对象的相互转换) 以fastJSON为实例
5、预习文件流(字节流、字符流)