跳到主要內容

JAVA 實用API

JAVA 實用API


  • String 、 StringBuilder和StringBuffer
比較:

功能
String StringBuilder StringBuffer
初始化 將物件加入到目前集合中一開始就配置記憶體空間 需要宣告物件,字串操作只會對同一塊記憶體操作 將物件加入到目前集合中
字串相加 + or  concat() append() 將物件加入到目前集合中
字串相減 delete(int start, int end) delete(int start, int end )
字串取代 replace(char oldChar, char newChar) replace(int start, int end, String str) replace(int start, int end, String str)
擷取子字串 subString(int start , int end)
subString(int start)
subString(int start , int end)
subString(int start)
subString(int start , int end)
subString(int start)
優點 簡單 1.Thread-safe:synchronized
2.減少記憶體的浪費
3. 程式效率佳
1減少記憶體的浪費
2. 程式效率更佳
缺點 浪費記憶體 non thread-safe

Ex: String 相加

/*****************************************************************************************************************
*   name : String相加範例
*   description:  +或是concat()
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {
String x = "Java" ;
x + "SCJP" ;
String y = "";
 y.concat("SCJP") ;
System.out.println(x);
System.out.println(y);

}

"+" 或是concat() :   不會改變x的內容值,所以x還是會印出 Java,要改變x的內容需要=
x = x + "SCJP" ,才會將x配置字串下去。

Ex: StringBuffer和StringBuilder
StringBuffer和StringBuilder的方法相同

/*****************************************************************************************************************
*   name : StringBuffer範例
*   description: 
StringBuffer 操作
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {
// TODO Auto-generated method stub
String x = "Java" ; 
x = x + "SCJP" ; 
String y = "";
y = y.concat("SCJP") ;

System.out.println(x);
System.out.println(y);

// StringBuffer
StringBuffer sb = new StringBuffer("It is a ");
sb.append("book") ;
System.out.println(sb);

sb.substring(6) ;
System.out.println(sb);
System.out.println(sb.substring(8));

int capacity = sb.capacity() ; 
System.out.println("容量:"+capacity);

int size = sb.length() ; 
System.out.println("字元數:"+size);

sb.delete(8,12);
System.out.println(sb);

sb.insert(sb.length(), "banana");
System.out.println(sb);

}


  • Autoboxing/Unboxing

Java 5.0開始就編譯器對自動幫你做Autobox和Unboxing的動作,以前需要

< Java 5.0
Integer number = new Integer(500) ;
int x = number.intValue() ;

>= Java 5.0以後
Integer number = 100  //AutoBoxing
int x = number             // unboxing

基本資料型態 AutoBoxing
Char '' , Character c = 'A'
Byte  Byte b = 10
Short Short t = 10 
Integer Integer i = 10 ;
Long Long l = 10L
Float Float f = 10.0F 
Double Double d = 10.0F
Boolean Boolean b = false

/*****************************************************************************************************************
*   name : 範例
*   description: 實作AutoBoxing / UnBoxing
*   author : Bryant
*****************************************************************************************************************/
    public static void main(String[] args) {
//autoboxing / unboxing

Integer number1 = 100 ;
int int1 = number1 ;
System.out.println(int1);

}
  • Formatter
Formatter類別位於java.text套件中,這個類別庫是用來規畫輸出格式,像: 貨幣、日期與message等等,NumberFormate可以字串格式的樣式。

(1) DecimalFormate
   public class DecimalFormate extends NumberFormat

/*****************************************************************************************************************
*   name : DecimaFormate l範例
*   description: 實作DecimalFormate字串,當我們使用自定格式化#符號去設計輸出內容
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {

        int cake = 10 ;
int total = cake * 10 ;
double percent = (double)cake / 12 ;

System.out.println("total is "+ total);
DecimalFormat d = new DecimalFormat("###.00") ;
DecimalFormat d2 = new DecimalFormat("000,000.00") ;
DecimalFormat d3 = new DecimalFormat(".##%");

System.out.println("total is "+ d.format(total));
System.out.println("total is "+ d2.format(total));
System.out.println("percent is "+ d3.format(percent));
}

結果:
total is 100
total is 100.00
total is 000,100.00
percent is 83.33%

NameDescription
#預留一個數字位置,沒有數字就不顯示
0預留一個數字位置,沒有數字就補上0
$貨幣符號
%百分比

(2) DateFormat
 public abstract class DateFormat extends Format

可以取得時間/日期的格式,為了可以取得各地方的時區可以利用Locale來搭配使用,


DateFormat

方法 描述
Calendar getCalendar() 指定給Calendar物件使用
DateFormat  getDateTimeInstance() 取得日期時間格式
DateFormat getDateTimeInstance(int dateStyle, int timeStyle) 取得日期時間格式
DateFormat  getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) 取得日期時間格式
DateFormat  getTimeInstance() 取得時間格式
DateFormat getTimeInstance(int style) 取得時間格式
DateFormat getTimeInstance(int style, Locale aLocale) 取得時間格式
TimeZone getTimeZone() 取得時區
void setTimeZone(TimeZone zone) 設定時區
void setNumberFormat(NumberFormat newNumberFormat) 設定數字格式
void setCalendar(Calendar newCalendar) 設定日曆
String format(Date date) 取得格式
abstract StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)

DateStyle
AttributeDescription
SHORT簡短顯示日期(2010/01/01)
MEDIUM中等顯示日期(2010/01/01)
LONG長格式顯示日期(2010/01/01)
FULL完整顯示日期(2012/01/01 sunday)

TimeStyle
AttributeDescription
SHORTpm,am
MEDIUM加入秒數
LONG長格式顯示日期(2010/01/01)
FULL完整顯示時間( )



/*****************************************************************************************************************
*   name : DateFormat範例
*   description: 顯示日期和時間顯示SHORT、MEDIUM、LOGN和FULL
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {
Date d = new Date();
DateFormat datef1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US ) ;
DateFormat datef2 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US ) ;
DateFormat datef3 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US ) ;
DateFormat datef4 = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US ) ;

System.out.println("Short DateTime Formate:"+ datef1.format(d) );
System.out.println("Short DateTime Formate:"+ datef2.format(d) );
System.out.println("Short DateTime Formate:"+ datef3.format(d) );
System.out.println("Short DateTime Formate:"+ datef4.format(d) );

}
結果:
Short DateTime Formate:10/9/13 9:20 PM
Short DateTime Formate:Oct 9, 2013 9:20:59 PM
Short DateTime Formate:October 9, 2013 9:20:59 PM CST
Short DateTime Formate:Wednesday, October 9, 2013 9:20:59 PM CST

(3) Formatter 格式化

Formatter建構子
建構子
描述
Formatter()
 
Formatter(Appendable a)
 
Formatter(Appendable a, Locale l)  
Formatter(File file)  
Formatter(File file, String csn)  
Formatter(File file, String csn, Locale l)  
Formatter(Locale l)   
Formatter(OutputStream os)  
Formatter(OutputStream os, String csn)  
Formatter(OutputStream os, String csn, Locale l)  
Formatter(PrintStream ps)  
Formatter(String fileName)  
Formatter(String fileName, String csn)  
Formatter(String fileName, String csn, Locale l)  

方法
描述
void close()
 關閉Formate
Formatter  format(Locale l, String format, Object... args)
 
Formatter format(String format, Object... args)  
ioException()  
locale()  
  • Regular Expressions

import : java.util.*
import: java.util.regex.*

正規化運算式常使用於搜尋或是字串的比對等等,

Name Description
. 任一字元
* 任意多個字元>=0
+ 任意多個字元>0
? 任意0個或是1個字元
- 範圍
| 分隔符號
^ 符合開頭字元
$ 符合解尾字元
[] 任意一個字元
[^] 非任意一個字元
{ n } 包含前面字元>=n個
{ n ,} 包含前面字元>n 個
{ n,m} 包含前面字元>n個, <m個
\W 不為字元
\s 等同於\t\r\f\n
\S 不為\t\r\f\n
\d 單一數值
\D 非單一數值


Ex1:

/*****************************************************************************************************************
*   name : Regex範例
*   description: 實作Regex搜尋功能
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {
String str ="It is a book.";
  Pattern patter = Pattern.compile("\\w+");
  Matcher matcher = patter.matcher(str) ; 
  while(matcher.find()){
  System.out.println(matcher.group());
  }
}

Pattern的方法
方法 描述
Pattern compile(String regex) 設定比對樣式予以編輯
Pattern compile(String regex, int flags) 設定比對樣式並設定旗標
String[] split(CharSequence input) 分割字串
String[] split(CharSequence input, int limit) 分割字串
Matcher matcher(CharSequence input) 是否符合正規化

flag標棋模式
方法 描述
CANON_EQ 完全正規劃相等
CASE_INSENSITIVE 忽略大小寫
COMMENTS 允許空白與註解
DOTALL 允許換行符號
LITERAL 直接分析
MULTILINE 多行模式
UNICODE_CASE 忽略大小寫
UNIX_LINES unix換行模式

/*****************************************************************************************************************
*   name : Regex範例
*   description: 實作Regex搜尋功能
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {

String str ="The phone number is 0911491538, Zip 1234 ";
Pattern patter = Pattern.compile("\\d{10}");
Matcher matcher = patter.matcher(str) ; 
while(matcher.find()){
System.out.println("電話: "+matcher.group());
}

}

Matcher 方法
Name Description
boolean find() 找出符合字串
boolean find(int start) 找出符合字串;參數是起始位置
String group() 回傳符合正規化的字串
String group(int group) 回傳符合正規化的字串; 參數為索引
int groupCount() 回傳群組的總數
boolean matches() 是否符合正規條件
Pattern pattern() 回傳符合
String replaceAll(String replacement) 取代字串

/*****************************************************************************************************************
*   name : 範例
*   description: 實作replace()
*   author : Bryant
*****************************************************************************************************************/
           public static void main(String[] args) {

String str ="The phone number is 0911491538, Zip 1234 ";
Pattern patter = Pattern.compile("(\\D)(\\d{3})(\\d{7})(\\D)");
Matcher matcher = patter.matcher(str) ;

while(matcher.find()){
 
String answer = matcher.replaceFirst("$1$2-$3$4");
System.out.println("電話: "+answer);
}
}

/*****************************************************************************************************************
*   name : 範例
*   description: 實作matcher()
*   author : Bryant
*****************************************************************************************************************/
public static void main(String[] args) {
 
String str ="JAVA 7";
Pattern patter = Pattern.compile("JAVA \\d", Pattern.CASE_INSENSITIVE);
Matcher matcher = patter.matcher(str) ;
System.out.println(matcher.matches());
}



















留言

這個網誌中的熱門文章

JavaBean 和POJO

前言 今天介紹JavaBean和POJO的不同,這兩個名詞在JAVA文章常常被拿來使用以及討論。在JDK1.1時候釋出才有的一個標準架構,很多時候常常被搞混,所以我們特別開闢一章來加以討論。POJO規範在企業級應用已經廣大的被使用的規範。 解釋 POJO : 全名為Plain-old-Java-object,只需要繼承Object就可以,沒有特定規定,只要建立的類別有setter/getter方法都可以稱為POJO JavaBean: JavaBean通常用來封裝多個物件成為單獨物件使用,規範比較嚴格,規則如下 規則 說明 1 需要實作序列(Serializable/Externalizable) 2 不能有參數的建構子( no-arg constructor) 3 需要有公用setter/getter 4 屬性必須要私人(private) 5 屬於特定POJO規則 比較 所有的JavaBean都為POJO,但是所有的POJO不一定為JavaBean 都可以當作重複元件 都必須序列化 特性都為可用性、易用性和持久化使用 - 應用 由圖我們可以知道POJO在應用程式中,主要用來存取資料庫資料達到持久化的目的,並提供給商業邏輯流程處理使用。這種POJO的架構提供程式人員開發時的可以很有規則將資料封裝並加以使用。 範例1. JavaBean(以員工為實例) JavaBean建立員工物件,可以發現Employee物件建構子沒有任何參數,屬性為私有化並setter/getter的命名方式。 //實作序列化 public class Employee implements java.io.Serializable{ private int id; private String name; //無參數建構子 public Employee(){} //以下實作setter/getter public void setId(int id){this.id=id;} public int getId(){return id;} public void setName(String ...

GSON基礎教學

GSON 前言 JSON是很常見的資料交換格式,在JAVA領域常用處理JSON的函式庫:GSON、FastXML和JSON-B,本章節會以GSON為主,學習目標如下 JSON格式說明 GSON 套件函式 GSON: 物件轉換JSON字串 GSON: JSON字串轉換物件 JSON 格式說明 JSON全名為JavaScript Object Notation,它是一種輕量級的資料交換格式,會大為流行的理由,主要是他比傳統用xml更輕巧且容易處理, JSON表達方式物件會用大括弧{},陣列則是用中括號[]。 用JSON字串來表達Employee的物件內容,由JSON字串可以知道物件name、age、sex和salary屬性。 JSON表示員工資料方式: {“name”:”Jack Bryant”, “age”:18, “sex”:”M”,”salary”:3500.00} JSON陣列表示方式: 跟我們使用JAVA的陣列方式類似,內容值可以是數字’、文字、布林、陣列、物件、null等等。 範例: 字串: [“紅”、”橙”、”黃”、”綠”、”青”、”藍”、”紫”} 布林: [true, true, false, false, true, true] GSON 套件函式 Gson為google所發布的函式庫,主要將物件與json字串之間的轉換時方便使用。當我們將JAVA物件轉換成JSON字串稱為 序列化 ,JSON字串轉換至JAVA物件稱為 反序列化 。 GSON: 物件轉換JSON字串 有了JSON基本概念後,我們進入本章重點,首先我們需要建立員工類別(Employee),定義如下 物件 屬性 員工類別 Employee name 名字 age 年紀 sex 性別 salary 薪水 /** * name:員工類別 */ public class Employee implements Serializable { //constructor public Employee(String name, double salary){ this.name = name; this.sala...

PHP與Python搭配

今天介紹如何利用php網頁呼叫目錄下的python程式工作或是資料交換,本人整理的方法有兩種 使用system()、exec()、shell_exec()呼叫程式 (1) string system ( string return_var ] ) 參考網址 官網解釋system()用來執行外部命令,返回為印出的結果,passthru()跟system()類似但是它不會返回結果。 範例1. 利用system執行ls指定並顯示在網頁上,無法使用變數保留ls的結果 檔案名稱: psystem.php $jsondata= system("ls -al", $result); 結果: (2) exec() : string exec ( string output [, int &$return_var ]] ) 參考網址 範例2. 利用exec執行python程式並可以回傳json格式給前端網頁做處理並顯示。我們ptopy.php就是可以看到callpy()為執行py的函式,它執行完pyEx01.py會將結果給$jsondata變數,做後面json解析。 檔案名稱: ptopy.php function callpy() { $jsondata= exec("/usr/bin/python pyEx01.py"); return $jsondata ; } $jsondata= callpy(); echo $jsondata ; echo " " ; $obj = json_decode($jsondata) ; echo "name:".$obj-> { 'name'} .',' ; echo "id:".$obj-> { 'id'} ; 檔案名稱: pyEx01.py import sys ...