Java300集——包装类-String-StringBuffer-StringBuilder-Date时间类-DateFormat-SimpleDateFormat-File类
基本数据类型的包装类
• 为什么需要 包装类(Wrapper Class) ?
• JAVA并不是纯面向对象的语言。 Java语言是一个面向对象的语言, 但是Java中的基本数据类型却是不面向对象的。 但是我们在实际使用中经常需要将基本数据转化成对象, 便于操作。 比如:集合的操作中。 这时, 我们就需要将基本类型数据转化成对象!
• 包装类均位于java.lang包, 包装类和基本数据类型的对应关系:
如何使用包装类?
• 包装类的作用:
• 提供: 字符串、 基本类型数据、 对象之间互相转化的方式!
• 包含每种基本数据类型的相关属性如最大值、 最小值等
• 所有的包装类(Wrapper Class)都有类似的方法, 掌握一个其他都类似! 以Integer为例!
package cn.bjsxt.test;
/**
* 测试包装类的基本用法
*
*/
public class Test01 {
public static void main(String[] args) {
Integer i = new Integer(1000);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(i));
Integer i2 = Integer.parseInt("234");
Integer i3 = new Integer("333");
System.out.println(i2.intValue());
String str = 234+"";
}
}
输出结果:2147483647
3e8
234
自动装箱和自动拆箱
• 自动装箱-boxing
• 基本类型就自动地封装到与它相同类型的包装中, 如:
Integer i = 100;
• 本质上是, 编译器编译时为我们添加了:
Integer i = Integer.valueOf(100);
• 自动拆箱autounboxing
• 包装类对象自动转换成基本类型数据。 如:
int a = new Integer(100);
• 本质上, 编译器编译时为我们添加了:
int a = new Integer(100).intValue();
package cn.bjsxt.test;
/**
* 测试自动装箱和拆箱
*
*/
public class Test02 {
public static void main(String[] args) {
// Integer a = new Integer(1000);
Integer a = 1000; //jdk5.0之后 . 自动装箱,编译器帮我们改进代码:Integer a = new Integer(1000);
Integer b = 2000;
int c = b; //自动拆箱,编译器改进:b.intValue();
System.out.println(c);
Integer d = 1234;
Integer d2 = 1234;
System.out.println(d==d2);
System.out.println(d.equals(d2));
System.out.println("###################");
Integer d3 = -100; //[-128,127]之间的数,仍然当做基本数据类型来处理。
Integer d4 = -100;
System.out.println(d3==d4);
System.out.println(d3.equals(d4));
}
}
结果:
2000
false
true
###################
true
true
String(不可变字符序列)
• Java字符串就是Unicode字符序列, 例如串“Java”就是4个Unicode字符J,a,v,a组成的。
• Java允许使用符号"+"把两个字符串连接起来
String s1 = “Hello”;
String s2 = “World!”;
String s = s1 + s2; //HelloWorld!
- String类的常用方法(1)
char charAt(int index)
• 返回字符串中第index个字符。
boolean equals(String other)
• 如果字符串与other相等, 返回true
boolean equalsIgnoreCase(String other)
• 如果字符串与other相等(忽略大小写) , 则返回true
int indexOf(String str) lastIndexOf()
int length()
• 返回字符串的长度。
String replace(char oldChar,char newChar)
• 返回一个新串, 它是通过用 newChar 替换此字符串中出现的所有oldChar而生成的
boolean startsWith(String prefix)
• 如果字符串以prefix开始, 则返回true
boolean endsWith(String prefix)
• 如果字符串以prefix结尾, 则返回true
• String substring(int beginIndex)
• String substring(int beginIndex,int endIndex)
• 返回一个新字符串, 该串包含从原始字符串beginIndex到串尾或endIndex-1的所有字符
String toLowerCase()
• 返回一个新字符串, 该串将原始字符串中的所有大写字母改成小写字母
String toUpperCase()
• 返回一个新字符串, 该串将原始字符串中的所有小写字母改成大写字母
String trim()
• 返回一个新字符串, 该串删除了原始字符串头部和尾部的空格
package cn.bjsxt.string;
/**
* String:不可变字符序列!
* 三个作业:
* 1. 练习String类的常用方法
* 2. 结合数组查看源码
* 3. 提高:按照老师的方法将String类中相关方法的源码看一看。
* @author dell
*
*/
public class TestString {
public static void main(String[] args) {
String str = new String("abcd");
String str2 = new String("abcd");
System.out.println(str2.equals(str)); //比较内容是否相等。true
System.out.println(str2==str); // false
System.out.println(str.charAt(2)); //c
String str3 = "def";
String str4 = "def";
System.out.println(str3.equals(str4)); //true
System.out.println(str3==str4); //true
System.out.println(str3.indexOf('y')); //-1
String s = str3.substring(0);
System.out.println(s); //def
String str5 = str3.replace('e', '*');
System.out.println(str5); //d*f
String str6 = "abcde,rrtt,cccee";
String[] strArray = str6.split(",");
for(int i=0;i<strArray.length;i++){
System.out.println(strArray[i]);
}
/*这里结果是:
abcde
rrtt
cccee */
String str7 = " aa bb ";
String str77 = str7.trim(); //去掉头和尾的空格
System.out.println(str77.length()); //6
System.out.println("Abc".equalsIgnoreCase("abc")); //true
System.out.println("Abcbd".indexOf('b')); //1
System.out.println("Abcbd".lastIndexOf('b')); //3
System.out.println("Abcbd".startsWith("Ab")); //true
System.out.println("Abcbd".endsWith("bd")); //true
System.out.println("Abcbd".toLowerCase()); //abcbd
System.out.println("Abcbd".toUpperCase()); //ABCBD
System.out.println("##################");
String gh = new String("a");
for (int i = 0; i < 10; i++) {
gh = gh + i;
}
System.out.println(gh); //a0123456789
}
}
字符串相等的判断(一般使用equals方法)
• equals判断字符串值相等, ==判断字符串对象引用相等!(若是指向同一个对象,则相等)
StringBuffer和StringBuilder
StringBuffer和StringBuilder非常类似, 均代表可变的字符序列, 而且方法也一样
• 查看API文档了解相关常用方法:
• append/delete/deleteCharAt/insert/inverse
package cn.bjsxt.stringbuilder;
/**
* 测试可变字符序列。StringBuilder(线程不安全,效率高),StringBuffer(线程安全,效率低)
* String:不可变字符序列
* @author dell
*
*/
public class Test01 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(); //字符数组长度初始为16
StringBuilder sb1 = new StringBuilder(32); //字符数组长度初始为32
StringBuilder sb2 = new StringBuilder("abcd"); //字符数组长度初始为32, value[]={'a','b','c','d',\u0000,\u0000...}
sb2.append("efg");
sb2.append(true).append(321).append("随便"); //通过return this实现方法链.
System.out.println(sb2);
System.out.println("##################");
StringBuilder gh = new StringBuilder("a");
for (int i = 0; i < 1000; i++) {
gh.append(i);
}
System.out.println(gh);
}
}
package cn.bjsxt.stringbuilder;
import java.util.ArrayList;
/**
* 测试StringBuilder的一些常用方法
* @author dell
*
*/
public class Test02 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
sb.delete(3, 5).delete(3, 5); //结果:abchijklmnopqrstuvwxyz
System.out.println(sb);
sb.reverse();
System.out.println(sb);
StringBuffer sb2 = new StringBuffer();
}
}
字符串选用
• String: 不可变字符序列
• StringBuilder: 可变字符序列、 效率高、 线程不安全
• StringBuilder: 可变字符序列、 效率低、 线程安全
• String使用陷阱:
string s="a"; //创建了一个字符串
s=s+"b"; //实际上原来的"a"字符串对象已经丢弃了, 现在又产生了一个字符串s+"b"。
如果多次执行这些改变串内容的操作, 会导致大量副本字符串对象存留在内存中, 降低效率。
如果这样的操作放到循环中, 会极大影响程序的性能。
Date时间类(java.util.Date)
• 在标准Java类库中包含一个Date类。 它的对象表示一个特定的瞬间, 精确到毫秒。
• Java中时间的表示说白了也是数字, 是从: 标准纪元1970.1.1 0点开始到某个时刻的毫秒数, 类型是long。
package cn.bjsxt.test;
import java.util.Date;
/**
* 测试Date类的用法
* @author dell
*
*/
public class TestDate {
public static void main(String[] args) {
Date d = new Date();
long t = System.currentTimeMillis(); //返回当前时间
System.out.println(t);
Date d2 = new Date(1000); //设置d2的时间值为1000,即1970-00:00:01
System.out.println(d2.toGMTString()); //不建议使用
d2.setTime(24324324);
System.out.println(d2.getTime());
System.out.println(d.getTime()<d2.getTime());
}
}
DateFormat和SimpleDateFormat
• 完成字符串和时间对象的转化!
• format
将时间转化成字符串
• parse
将字符串解析为时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,属于本月的第W周");
父类引用指向子类对象
package cn.bjsxt.test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateFormat {
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,属于本月的第W周");
Date d = new Date(12321314323L);
String str = df.format(d); //将时间对象按照格式化字符串,转化成字符串
System.out.println(str); //1970-01-02 06:13:33
System.out.println("####################");
String str2 = "1977-7-7";
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d2 = df2.parse(str2); //将字符串解析为时间
System.out.println(d2);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Calendar日历类
• 人们对于时间的认识是: 某年某月某日, 这样的日期概念。 计算机是long类型的数字。
通过Calendar在二者之间搭起桥梁!
GregorianCalendar公历
• GregorianCalendar 是 Calendar 的一个具体子类, 提供了世界上大多数国家/地区使用的标准日历系统。
• 注意:
• 月份: 一月是0, 二月是1, 以此类推, 是12月是11
• 星期: 周日是1, 周一是2, 。 。 。 周六是7
package cn.bjsxt.test;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 测试日期类
* @author dell
*
*/
public class TestCalendar {
public static void main(String[] args) {
Calendar c = new GregorianCalendar();
c.set(2001, Calendar.FEBRUARY, 10, 12, 23, 34);
// c.set(Calendar.YEAR, 2001);
// c.set(Calendar.MONTH, 1); //二月
// c.set(Calendar.DATE, 10);
// c.setTime(new Date());
Date d = c.getTime();
System.out.println(d);
System.out.println(c.get(Calendar.YEAR));
//测试日期计算
c.add(Calendar.MONTH, -30);
System.out.println(c);
}
}
可视化日历
package cn.bjsxt.test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
* 可视化日历程序
*
*/
public class VisualCalendar {
public static void main(String[] args) {
System.out.println("请输入日期(按照格式:2030-3-10):");
Scanner scanner = new Scanner(System.in);
String temp = scanner.nextLine();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(temp);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int day = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, 1);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for(int i=1;i<calendar.get(Calendar.DAY_OF_WEEK);i++){
System.out.print('\t');
}
for(int i=1;i<=maxDate;i++){
if(i==day){
System.out.print("*");
}
System.out.print(i+"\t");
int w = calendar.get(Calendar.DAY_OF_WEEK);
if(w==Calendar.SATURDAY){
System.out.print('\n');
}
calendar.add(Calendar.DATE, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
File类
• 文件和目录路径名的抽象表示形式。 一个File对象可以代表一个文件或目录
• 可以实现获取文件和目录属性等功能
• 可以实现对文件和目录的创建、 删除等功能
• File不能访问文件内容
File file = new File("d:\\test\\java.txt");
File file = new File("d:/test/java.txt");
File file = new File("java.txt");
路径可以是绝对路径和相对路径, 分隔符采用\或者/
• 通过File对象可以访问文件的属性。
public String getName()
public String getPath()
public boolean isFile()
public boolean isDirectory()
public boolean canRead()
public boolean canWrite()
public boolean exists()
public long length()
public boolean isHidden()
public long lastModified() //最后一次修改
public File[] listFiles();
• 通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下) 。
• public boolean createNewFile()throws IOException
• public boolean delete()
• public boolean mkdir(), mkdirs() 注意两个的区别! !
package cn.bjsxt.test.file;
import java.io.File;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) {
File f = new File("d:/src3/TestObject.java");
File f2 = new File("d:/src3");
File f3 = new File(f2,"TestThis.java");
File f4 = new File(f2,"TestFile666.java");
File f5 = new File("d:/src3/aa/bb/cc/ee/ddd");
f5.mkdirs(); //用mkdir()则报错
//f4.createNewFile();
// f4.delete();
if(f.isFile()){
System.out.println("是一个文件");
}
if(f2.isDirectory()){
System.out.println("是一个目录");
}
}
}
package cn.bjsxt.test.file;
import java.io.File;
public class FileTree {
public static void main(String[] args) {
//找一个自己硬盘上有用的文件夹
File f = new File("d:/src3");
printFile(f, 0);
}
static void printFile(File file,int level){
for (int i = 0; i < level; i++) {
System.out.print("-");
}
System.out.println(file.getName());
if(file.isDirectory()){
File[] files = file.listFiles();
for (File temp : files) {
printFile(temp, level+1);
}
}
}
}