您的位置:首页 > 编程语言 > Java开发

Java常用类库(一)

2011-08-31 11:42 211 查看

Java常用类库(一)

----------------------
认识StringBuffer

StringBuffer是使用缓冲区的,本身也是操作字符串的,但是与String类不同,String类的内容一旦声明之后则不可改变,改变的只是其内存地址的指赂,而StringBuffer中的内容是可以改变的。对StringBufffer而言,本身是一个具体的操作类,所以不能像String那样采用直接赋值的方式进行对象的实例化,必须通过构造方法完成

StringBuffer连接字符操作:

String用“+”连接 “Hello” + “ ” + “World”

StringBuffer用append “Hello” append “ ” append “World”

实例操作:字符串连接

public class StringBufferDemo01{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("Hello ") ;                               // 向StringBuffer中添加内容
buf.append("World").append("!!!") ;           // 可以连续调用append()方法
buf.append("\n") ;                                     // 添加一个转义字符
buf.append("数字 = ").append(1).append("\n") ; // 添加数字
buf.append("字符 = ").append('C').append("\n");       // 添加字符
buf.append("布尔 = ").append(true) ;  // 添加布尔值
System.out.println(buf) ;                     // 直接输出对象,调用toString()
}
};


实例二:在任意位置处为StringBuffer添加内容,可直接使用inster()方法

public class StringBufferDemo03{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("World!!") ;        // 添加内容
buf.insert(0,"Hello ") ;          // 在第一个内容之前添加内容
System.out.println(buf) ;
buf.insert(buf.length(),"MLDN~") ;     // 在最后添加内容
System.out.println(buf) ;
}
};


实例三:字符吕反转操作,可直接使用reverse()方法就可以完成反转的功能

public class StringBufferDemo04{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("World!!") ;        // 添加内容
buf.insert(0,"Hello ") ;          // 在第一个内容之前添加内容
String str = buf.reverse().toString() ;    // 将内容反转后变为String类型
System.out.println(str) ;        // 将内容输出
}
};


实例四:替换指定范围的内容:可直接使用replace()方法

public class StringBufferDemo05{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("Hello ").append("World!!") ;          // 向StringBuffer添加内容
buf.replace(6,11,"LiXingHua") ;          // 将world的内容替换
System.out.println("内容替换之后的结果:" + buf) ;       // 输出内容
}
};


实例五:字符串截取,可直接使用substring()方法

public class StringBufferDemo06{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("Hello ").append("World!!") ;          // 向StringBuffer添加内容
buf.replace(6,11,"LiXingHua") ;          // 将world的内容替换
String str = buf.substring(6,15) ;   // 截取指定范围的内容
System.out.println("内容替换之后的结果:" + str) ; // 输出内容
}
};


实例六:字符删除,可直接使用delete()方法

public class StringBufferDemo07{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("Hello ").append("World!!") ;          // 向StringBuffer添加内容
buf.replace(6,11,"LiXingHua") ;          // 将world的内容替换
String str = buf.delete(6,15).toString() ;      // 删除指定范围中的内容
System.out.println("删除之后的结果:" + str) ; // 输出内容
}
};


实例七:查找指定内容是否存在

public class StringBufferDemo08{
public static void main(String args[]){
StringBuffer buf = new StringBuffer() ;      // 声明StringBuffer对象
buf.append("Hello ").append("World!!") ;          // 向StringBuffer添加内容
if(buf.indexOf("Hello")==-1){
System.out.println("没有查找到指定的内容") ;
}else{     // 不为01表示查找到内容
System.out.println("可以查找到指定的内容") ;
}
}
};


Runtime类

Runtime运行时,是一个封装了JVM进程的类,每一个JAVA程序实际上都是启动了一个JVM进程,那么每一个JVM进程都是对应这一个Runtime实例,此实例是由JVM为其实例化的。本类的定义中根本就没有构造方法,本类的构造方法被私有化了,则在此类中肯定有一个方法可以返回本类的实例化对象。public static Runtime getRuntime()

实例:利用Runtime得到JVM信息

public class RuntimeDemo01{
public static void main(String args[]){
Runtime run = Runtime.getRuntime();  // 通过Runtime类的静态方法进行实例化操作
System.out.println("JVM最大内存量:" + run.maxMemory()) ;     // 观察最大的内存,根据机器的不同,环境也会有所不同
System.out.println("JVM空闲内存量:" + run.freeMemory()) ;      // 取得程序运行的空闲内存
String str = "Hello " + "World" + "!!!"
+"\t" + "Welcome " + "To " + "MLDN" + "~" ;
System.out.println(str) ;
for(int x=0;x<1000;x++){
str += x ;               // 循环修改内容,会产生多个垃圾
}
System.out.println("操作String之后的,JVM空闲内存量:" + run.freeMemory()) ;
run.gc() ;        // 进行垃圾收集,释放空间
System.out.println("垃圾回收之后的,JVM空闲内存量:" + run.freeMemory()) ;
}
};


Runtime与Process类

除了观察内存使用量外,也可以直接使用Runtime类运行本机的可执行程序,例如调用记事本。public Process exec(String command) throws IOException,并可以通过deestroy()方法销毁一个进程。

public class RuntimeDemo03{
public static void main(String args[]){
Runtime run = Runtime.getRuntime() ; // 取得Runtime类的实例化对象
Process p = null ;   // 定义进程变量
try{
p = run.exec("notepad.exe") ;       // 调用本机程序,此方法需要异常处理
}catch(Exception e){
e.printStackTrace() ;      // 打印异常信息
// System.out.println(e) ;
}
try{
Thread.sleep(5000) ;      // 让此线程存活5秒
}catch(Exception e){
}
p.destroy() ;    // 结束此进程
}
};


国际化程序

国际化程序就是指一个程序可以同时适应多门语言,即:如果现在程序使用者是中国人,则会以中文为显示文字,如果现在程序的使用者是英国人,则会以英语为显示的文字,也就是说可以通过国际化操作,让一个程序适应各个国家的语言要求。

国际化程序实现支持的类

n java.util.Locale:用于表示一个国家语言的类。

n java.util.ResourceBundle:用于访问资源文件。

n java.text.MessageFormat:格式化资源文件的占位字符串。

Locale类

Locale表示本地,实际上使用的是一个ISO编码的封装类,对于各个国家来说都存在一个唯一的编码,那么这种编码就称为ISO编码,使用Locale可以指定好一个具体的国家编码。

例:汉语:zh-CN 英语:en-US 法语:fr-FR

ResourceBundle类

此类是专门完成属性文件读取操作的,读取的时候直接指定文件名称即可,可以根据Locale所指定的区域码来自动选择所需要的资源文件。

JAVA国际化程序实现

可以根据国家不同,输出不同国家的你好:

汉语:你好!

英语:Hello!

法语:Bonjour!

分别定义在不同的资源文件中。

汉语:Message_zh_CN.properties

英语:Message_en_US.properties

法语:Message_fr_FR.properties

实例:

import java.util.ResourceBundle ;

import java.util.Locale ;

public class InterDemo02{
public static void main(String args[]){
Locale zhLoc = new Locale("zh","CN") ;            // 表示中国地区
Locale enLoc = new Locale("en","US") ;            // 表示美国地区
Locale frLoc = new Locale("fr","FR") ;              // 表示法国地区
// 找到汉语的属性文件,需要指定中文的Locale对象
ResourceBundle zhrb = ResourceBundle.getBundle("Message",zhLoc) ;
// 找到英语的属性文件,需要指定英文的Locale对象
ResourceBundle enrb = ResourceBundle.getBundle("Message",enLoc) ;
// 找到法语的属性文件,需要指定法文的Locale对象
ResourceBundle frrb = ResourceBundle.getBundle("Message",frLoc) ;
// 依次读取各个属性文件的内容,通过键值读取,此时的键值名称统一为info
System.out.println("汉语" + zhrb.getString("info")) ;
System.out.println("英语:" + enrb.getString("info")) ;
System.out.println("法语:" + frrb.getString("info")) ;
}
};

处理动态文本

之前的资源文件中的所有内容实际上都是固定的,而如果现在有些内容,“你好!XXX”。那么此时就必须在资原文件中进行一些动态文本的配置,设置占位符,这些符号中的内容暂时不固定,而是在程序执行的时候由程序进行设置的,而要想实现这样的功能,则必须使用MessageForm类。此类是在java.text包中定义的。

占位符使用{数字}表示

实例:

import java.util.ResourceBundle ;

import java.util.Locale ;

import java.text.* ;

public class InterDemo03{
public static void main(String args[]){
Locale zhLoc = new Locale("zh","CN") ;            // 表示中国地区
Locale enLoc = new Locale("en","US") ;            // 表示美国地区
Locale frLoc = new Locale("fr","FR") ;              // 表示法国地区
// 找到中文的属性文件,需要指定中文的Locale对象
ResourceBundle zhrb = ResourceBundle.getBundle("Message",zhLoc) ;
// 找到英文的属性文件,需要指定英文的Locale对象
ResourceBundle enrb = ResourceBundle.getBundle("Message",enLoc) ;
// 找到法文的属性文件,需要指定法文的Locale对象
ResourceBundle frrb = ResourceBundle.getBundle("Message",frLoc) ;
// 依次读取各个属性文件的内容,通过键值读取,此时的键值名称统一为info
String str1 = zhrb.getString("info") ;
String str2 = enrb.getString("info") ;
String str3 = frrb.getString("info") ;
System.out.println("中文:" + MessageFormat.format(str1,"李兴华")) ;
System.out.println("英语:" + MessageFormat.format(str2,"LiXingHua")) ;
System.out.println("法语:" + MessageFormat.format(str3,"LiXingHua")) ;
}
};


JAVA新特性——可变参数

实例:

public class InterDemo04{
public static void main(String args[]){
System.out.print("第一次运行:") ;
fun("LXH","Li","李兴华") ; // 传入三个参数
System.out.print("\n第二次运行:") ;
fun("MLDN") ;                           // 传入一个参数
}
public static void fun(Object...args){    // 固定语法,输入任意多个数据,使用数组表示
for(int i=0;i<args.length;i++){
System.out.print(args[i] + "、") ;
}
}
};


System类

System.out.println()本身就是一个系统提供好的类,而且out.println()方法也是经常使用到的。

System类是一些与系统相关的属性和方法的集合在System类中所有的属性都是静态的

实例:利用System获取一个操作的运行时间

public class SystemDemo01{
public static void main(String args[]){
long startTime = System.currentTimeMillis() ;    // 取得开始计算之前的时间
int sum = 0 ;                 // 声明变量
for(int i=0;i<30000000;i++){       // 执行累加操作
sum += i ;
}
long endTime = System.currentTimeMillis() ;     // 取得计算之后的时间
// 结束时间减去开始时间
System.out.println("计算所花费的时间:" + (endTime-startTime) +"毫秒") ;
}
};


实例:列出本机的全部系统属性

public class SystemDemo02{
public static void main(String args[]){
System.getProperties().list(System.out) ;     // 列出系统的全部属性
}
};

如果只想要其中几个属性的话:

public class SystemDemo03{
public static void main(String args[]){
System.out.println("系统版本:" + System.getProperty("os.name")
+ System.getProperty("os.version")
+ System.getProperty("os.arch")) ;
System.out.println("系统用户:" + System.getProperty("user.name")) ;
System.out.println("当前用户目录:" + System.getProperty("user.home")) ;
System.out.println("当前用户工作目录:" + System.getProperty("user.dir")) ;
}
};

垃圾对象的回收

一个对象如果不使用,则肯定要等待进行垃圾收集,垃圾收集可以自动调用也可以手工调用,手工调用的时候就是调用System.gc()或者Runtime.getRuntime().gc()。但是如量一个地象在回收之前需要做一些收尾工作,则就必须覆写Object类中的:

protected void finalize() throws Throwable

实例:

class Person{
private String name ;
private int age ;
public Person(String name,int age){
this.name = name ;
this.age = age;
}
public String toString(){       // 覆写toString()方法
return "姓名:" + this.name + ",年龄:" + this.age ;
}
public void finalize() throws Throwable{     // 对象释放空间时默认调用此方法
System.out.println("对象被释放 --> " + this) ;
}
};

public class SystemDemo04{
public static void main(String args[]){
Person per = new Person("张三",30) ;
per = null ;     // 断开引用
System.gc() ;         // 强制性释放空间
}
};

日期操作类(Date、Calendar)

Date类是一个较为常用的类,但是其操作的日期格式会有一些不符合个人的要求,而如果想进一步取得一些自己需要的时间,则可以使用Calendar类。

Date类

在java.util包中定义了Date类,Date类本身使用非常简单,直接输出其实例化对象即可。

import java.util.Date ;
public class DateDemo01{
public static void main(String args[]){
Date date = new Date() ;       // 直接实例化Date对象
System.out.println("当前日期为:" + date) ;
}
};

Calendar类

使用此类可以直接将日期精确到毫秒

Calendar类是一个抽象类,既然是一个抽象类则肯定无法直接使用,此时就要利用对象多态性的概念,通过向上转型关系实例化本类对象

实例:

import java.util.* ;
public class DateDemo02{
public static void main(String args[]){
Calendar calendar = new GregorianCalendar();    // 实例化Calendar类对象
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + (calendar.get(Calendar.MONTH) + 1));
System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
}
};

日期操作类(DateFormat、SimpleDateFormat)

DateFormat类

此类是一个日期的格式化类,专门格式化日期的操作,因为java.util.Date类本身就已经包含了完整的期,所以只需要将此日期按照一些格式格式化显示即可。

实例:

import java.text.DateFormat ;
import java.util.Date ;
public class DateDemo03{
public static void main(String args[]){
DateFormat df1 = null ;        // 声明一个DateFormat
DateFormat df2 = null ;        // 声明一个DateFormat
df1 = DateFormat.getDateInstance() ;   // 得到日期的DateFormat对象
df2 = DateFormat.getDateTimeInstance() ;   // 得到日期时间的DateFormat对象
System.out.println("DATE:" + df1.format(new Date())) ; // 按照日期格式化
System.out.println("DATETIME:" + df2.format(new Date())) ;      // 按照日期时间格式化
}
};

SimpleDateFormat类

此类的功能是完成日期的显示格式化。如果想要实现转换则必须先准备好一个模板,通过此模板进行日期数字的提取工作。

实例:

import java.text.* ;
import java.util.* ;
public class DateDemo05{
public static void main(String args[]){
String strDate = "2008-10-19 10:11:30.345" ;
// 准备第一个模板,从字符串中提取出日期数字
String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;
// 准备第二个模板,将提取后的日期数字变为指定的格式
String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;
SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ;         // 实例化模板对象
SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ;         // 实例化模板对象
Date d = null ;
try{
d = sdf1.parse(strDate) ; // 将给定的字符串中的日期提取出来
}catch(Exception e){                   // 如果提供的字符串格式有错误,则进行异常处理
e.printStackTrace() ;             // 打印异常信息
}
System.out.println(sdf2.format(d)) ;     // 将日期变为新的格式
}
};


实例操作:取得当前日期

基于Calendar类操作:

import java.util.* ; // 导入需要的工具包
class DateTime{            // 以后直接通过此类就可以取得日期时间
private Calendar calendar = null ;         // 声明一个Calendar对象,取得时间
public DateTime(){                                          // 构造方法中直接实例化对象
this.calendar = new GregorianCalendar() ;
}
public String getDate(){        // 得到的是一个日期:格式为:yyyy-MM-dd HH:mm:ss.SSS
// 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能
StringBuffer buf = new StringBuffer() ;
buf.append(calendar.get(Calendar.YEAR)).append("-") ;    // 增加年
buf.append(this.addZero(calendar.get(Calendar.MONTH)+1,2)).append("-") ;   // 增加月
buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH),2)).append(" ") ;     // 取得日
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY),2)).append(":") ; // 取得时
buf.append(this.addZero(calendar.get(Calendar.MINUTE),2)).append(":") ;
buf.append(this.addZero(calendar.get(Calendar.SECOND),2)).append(".") ;
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND),3)) ;
return buf.toString() ;
}
public String getDateComplete(){        // 得到的是一个日期:格式为:yyyy年MM月dd日 HH时mm分ss秒SSS毫秒
// 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能
StringBuffer buf = new StringBuffer() ;
buf.append(calendar.get(Calendar.YEAR)).append("年") ;  // 增加年
buf.append(this.addZero(calendar.get(Calendar.MONTH)+1,2)).append("月") ;       // 增加月
buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH),2)).append("日") ;   // 取得日
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY),2)).append("时") ;      // 取得时
buf.append(this.addZero(calendar.get(Calendar.MINUTE),2)).append("分") ;          // 取得分
buf.append(this.addZero(calendar.get(Calendar.SECOND),2)).append("秒") ;          // 取得秒
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND),3)).append("毫秒") ;    // 取得毫秒
return buf.toString() ;
}
public String getTimeStamp(){            // 得到的是一个时间戳
// 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能
StringBuffer buf = new StringBuffer() ;
buf.append(calendar.get(Calendar.YEAR)) ; // 增加年
buf.append(this.addZero(calendar.get(Calendar.MONTH)+1,2)) ;      // 增加月
buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH),2)) ;  // 取得日
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY),2)) ;     // 取得时
buf.append(this.addZero(calendar.get(Calendar.MINUTE),2)) ;         // 取得分
buf.append(this.addZero(calendar.get(Calendar.SECOND),2));          // 取得秒
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND),3)) ;      // 取得毫秒
return buf.toString() ;
}
// 考虑到日期中存在前导0,所以在此处加上补零的方法
private String addZero(int num,int len){
StringBuffer s = new StringBuffer() ;
s.append(num) ;
while(s.length()<len){   // 如果长度不足,则继续补0
s.insert(0,"0") ;      // 在第一个位置处补0
}
return s.toString() ;
}
};
public class DateDemo06{
public static void main(String args[]){
DateTime dt = new DateTime() ;
System.out.println("系统日期:"+dt.getDate()) ;
System.out.println("中文日期:"+dt.getDateComplete()) ;
System.out.println("时间戳:"+dt.getTimeStamp()) ;
}
};


基于SimpleDateFormat类操作:

实例:

import java.util.* ; // 导入需要的工具包
import java.text.* ; // 导入SimpleDateFormat所在的包
class DateTime{            // 以后直接通过此类就可以取得日期时间
private SimpleDateFormat sdf = null ;  // 声明SimpleDateFormat对象
public String getDate(){        // 得到的是一个日期:格式为:yyyy-MM-dd HH:mm:ss.SSS
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
return this.sdf.format(new Date()) ;// 将当前日期进行格式化操作
}
public String getDateComplete(){        // 得到的是一个日期:格式为:yyyy年MM月dd日 HH时mm分ss秒SSS毫秒
this.sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS毫秒") ;
return this.sdf.format(new Date()) ;// 将当前日期进行格式化操作
}
public String getTimeStamp(){            // 得到的是一个时间戳
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS") ;
return this.sdf.format(new Date()) ;// 将当前日期进行格式化操作
}
};
public class DateDemo07{
public static void main(String args[]){
DateTime dt = new DateTime() ;
System.out.println("系统日期:"+dt.getDate()) ;
System.out.println("中文日期:"+dt.getDateComplete()) ;
System.out.println("时间戳:"+dt.getTimeStamp()) ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: