當前位置:學者齋 >

IT認證 >計算機等級 >

JAVA常用程式碼積累

JAVA常用程式碼積累

Java是一個面向物件的語言。對程式設計師來說,這意味著要注意應中的資料和操縱資料的`方法(method),而不是嚴格地用過程來思考。下面是小編整理的關於JAVA常用程式碼積累,希望大家認真閱讀!

JAVA常用程式碼積累

  1.獲取環境變數

nv(“PATH”);

nv(“JAVA_HOME”);

  2.獲取系統屬性

roperty(“pencil color”); // 得到屬性值

java -Dpencil color=green

roperty(“ion”); // 得到Java版本號

Properties p = roperties(); // 得到所有屬性值

();

  ng Tokenizer

// 能夠同時識別, 和 |

StringTokenizer st = new StringTokenizer(“Hello, World|of|Java”, “, |”);

while (oreElements()) {

Token();

}

// 把分隔符視為token

StringTokenizer st = new StringTokenizer(“Hello, World|of|Java”, “, |”, true);

  ngBuffer(同步)和StringBuilder(非同步)

StringBuilder sb = new StringBuilder();

nd(“Hello”);

nd(“World”);

ring();

new StringBuffer(a)rse(); // 反轉字串

  5. 數字

// 數字與物件之間互相轉換 – Integer轉int

alue();

// 浮點數的舍入

d()

// 數字格式化

NumberFormat

// 整數 -> 二進位制字串

toBinaryString()或valueOf()

// 整數 -> 八進位制字串

toOctalString()

// 整數 -> 十六進位制字串

toHexString()

// 數字格式化為羅馬數字

RomanNumberFormat()

// 隨機數

Random r = new Random();

Double();

Int();

  6. 日期和時間

// 檢視當前日期

Date today = new Date();

nstance()ime();

// 格式化預設區域日期輸出

DateFormat df = nstance();

at(today);

// 格式化制定區域日期輸出

DateFormat df_cn = ateInstance(, A);

String now = df_at(today);

// 按要求格式列印日期

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);

at(today);

// 設定具體日期

GregorianCalendar d1 = new GregorianCalendar(2009, 05, 06); // 6月6日

GregorianCalendar d2 = new GregorianCalendar(); // 今天

Calendar d3 = nstance(); // 今天

ime(); // Calendar或GregorianCalendar轉成Date格式

(, 1999);

(H, L);

(_OF_MONTH, 12);

// 字串轉日期

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);

Date now = e(String);

// 日期加減

Date now = new Date();

long t = ime();

t += 700*24*60*60*1000;

Date then = new Date(t);

Calendar now = nstance();

(, -2);

// 計算日期間隔(轉換成long來計算)

ime() – ime();

// 比較日期

Date型別,就使用equals(), before(), after()來計算

long型別,就使用==, <, >來計算

// 第幾日

使用Calendar的get()方法

Calendar c = nstance();

();

// 記錄耗時

long start = entTimeMillis();

long end = entTimeMillis();

long elapsed = end – start;

Time(); //毫秒

// 長整形轉換成秒

ring(t/1000D);

  7.結構化資料

// 陣列拷貝

yCopy(oldArray, 0, newArray, 0, th);

// ArrayList

add(Object o) // 在末尾新增給定元素

add(int i, Object o) // 在指定位置插入給定元素

clear() // 從集合中刪除全部元素

Contains(Object o) // 如果Vector包含給定元素,返回真值

get(int i) // 返回指定位置的物件控制代碼

indexOf(Object o) // 如果找到給定物件,則返回其索引值;否則,返回-1

remove(Object o) // 根據引用刪除物件

remove(int i) // 根據位置刪除物件

toArray() // 返回包含集合物件的陣列

// Iterator

List list = new ArrayList();

Iterator it = ator();

while (ext())

Object o = ();

// 連結串列

LinkedList list = new LinkedList();

ListIterator it = Iterator();

while (ext())

Object o = ();

// HashMap

HashMap hm = new HashMap();

(key); // 通過key得到value

(“No1”, “Hexinyu”);

(“No2”, “Sean”);

// 方法1: 獲取全部鍵值

Iterator it = es()ator();

while (ext()) {

String myKey = ();

String myValue = (myKey);

}

// 方法2: 獲取全部鍵值

for (String key : et()) {

String myKey = key;

String myValue = (myKey);

}

// Preferences – 與系統相關的使用者設定,類似名-值對

Preferences prefs = NodeForPackage(s);

String text = (“textFontName”, “lucida-bright”);

String display = (“displayFontName”, “lucida-balckletter”);

tln(text);

tln(display);

// 使用者設定了新值,儲存回去

(“textFontName”, “new-bright”);

(“displayFontName”, “new-balckletter”);

// Properties – 類似名-值對,key和value之間,可以用”=”,”:”或空格分隔,用”#”和”!”註釋

InputStream in = lassLoader()esourceAsStream(“erties”);

Properties prop = new Properties();

(in);

e();

roperty(key, value);

roperty(key);

// 排序

1. 陣列:(strings);

2. List:(list);

3. 自定義類:class SubComp implements Comparator

然後使用(strings, new SubComp())

// 兩個介面

1. arable: 提供物件的自然排序,內置於類中

int compareTo(Object o);

boolean equals(Object o2);

2. arator: 提供特定的比較方法

int compare(Object o1, Object o2)

// 避免重複排序,可以使用TreeMap

TreeMap sorted = new TreeMap(unsortedHashMap);

// 排除重複元素

Hashset hs – new HashSet();

// 搜尋物件

binarySearch(): 快速查詢 – Arrays, Collections

contains(): 線型搜尋 – ArrayList, HashSet, Hashtable, linkedList, Properties, Vector

containsKey(): 檢查集合物件是否包含給定 – HashMap, Hashtable, Properties, TreeMap

containsValue(): 主鍵(或給定值) – HashMap, Hashtable, Properties, TreeMap

indexOf(): 若找到給定物件,返回其位置 – ArrayList, linkedList, List, Stack, Vector

search(): 線型搜素 – Stack

// 集合轉陣列

toArray();

// 集合總結

Collection: Set – HashSet, TreeSet

Collection: List – ArrayList, Vector, LinkedList

Map: HashMap, HashTable, TreeMap

  8. 泛型與foreach

// 泛型

List myList = new ArrayList();

// foreach

for (String s : myList) {

tln(s);

}

  9.面向物件

// toString()格式化

public class ToStringWith {

int x, y;

public ToStringWith(int anX, int aY) {

x = anX;

y = aY;

}

public String toString() {

return “ToStringWith[” + x + “,” + y + “]”;

}

public static void main(String[] args) {

tln(new ToStringWith(43, 78));

}

}

// 覆蓋equals方法

public boolean equals(Object o) {

if (o == this) // 優化

return true;

if (!(o instanceof EqualsDemo)) // 可投射到這個類

return false;

EqualsDemo other = (EqualsDemo)o; // 型別轉換

if (int1 != 1) // 按欄位比較

return false;

if (!ls(1))

return false;

return true;

}

// 覆蓋hashcode方法

private volatile int hashCode = 0; //延遲初始化

public int hashCode() {

if (hashCode == 0) {

int result = 17;

result = 37 * result + areaCode;

}

return hashCode;

}

// Clone方法

要克隆物件,必須先做兩步: 1. 覆蓋物件的clone()方法; 2. 實現空的Cloneable介面

public class Clone1 implements Cloneable {

public Object clone() {

return e();

}

}

// Finalize方法

Object f = new Object() {

public void finalize() {

tln(“Running finalize()”);

}

};

untime()hutdownHook(new Thread() {

public void run() {

tln(“Running Shutdown Hook”);

}

});

在呼叫(0);的時候,這兩個方法將被執行

// Singleton模式

// 實現1

public class MySingleton() {

public static final MySingleton INSTANCE = new MySingleton();

private MySingleton() {}

}

// 實現2

public class MySingleton() {

public static MySingleton instance = new MySingleton();

private MySingleton() {}

public static MySingleton getInstance() {

return instance;

}

}

// 自定義異常

Exception: 編譯時檢查

RuntimeException: 執行時檢查

public class MyException extends RuntimeException {

public MyException() {

super();

}

public MyException(String msg) {

super(msg);

}

}

  10. 輸入和輸出

// Stream, Reader, Writer

Stream: 處理位元組流

Reader/Writer: 處理字元,通用Unicode

// 從標準輸入裝置讀資料

1. 用的BufferedInputStream()讀取位元組

int b = ();

tln(“Read data: ” + (char)b); // 強制轉換為字元

2. BufferedReader讀取文字

如果從Stream轉成Reader,使用InputStreamReader類

BufferedReader is = new BufferedReader(new

InputStreamReader());

String inputLine;

while ((inputLine = Line()) != null) {

tln(inputLine);

int val = eInt(inputLine); // 如果inputLine為整數

}

e();

// 向標準輸出裝置寫資料

1. 用的println()列印資料

2. 用PrintWriter列印

PrintWriter pw = new PrintWriter();

tln(“The answer is ” + myAnswer + ” at this time.”);

// Formatter類

格式化列印內容

Formatter fmtr = new Formatter();

at(“%1$04d – the year of %2$f”, 1951, );

或者tf();或者at();

// 原始掃描

void doFile(Reader is) {

int c;

while ((c = ()) != -1) {

tln((char)c);

}

}

// Scanner掃描

Scanner可以讀取File, InputStream, String, Readable

try {

Scanner scan = new Scanner(new File(“”));

while (ext()) {

String s = ();

}

} catch (FileNotFoundException e) {

tStackTrace();

}

}

// 讀取檔案

BufferedReader is = new BufferedReader(new FileReader(“”));

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“”));

e();

e();

// 複製檔案

BufferedIutputStream is = new BufferedIutputStream(new FileIutputStream(“”));

BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(“”));

int b;

while ((b = ()) != -1) {

e(b);

}

e();

e();

// 檔案讀入字串

StringBuffer sb = new StringBuffer();

char[] b = new char[8192];

int n;

// 讀一個塊,如果有字元,加入緩衝區

while ((n = (b)) > 0) {

nd(b, 0, n);

}

return ring();

// 重定向標準流

String logfile = “”;

rr(new PrintStream(new FileOutputStream(logfile)));

// 讀寫不同字符集文字

BufferedReader chinese = new BufferedReader(new InputStreamReader(new FileInputStream(“”), “ISO8859_1”));

PrintWriter standard = new PrintWriter(new OutputStreamWriter(new FileOutputStream(“”), “UTF-8”));

// 讀取二進位制資料

DataOutputStream os = new DataOutputStream(new FileOutputStream(“”));

eInt(i);

eDouble(d);

e();

// 從指定位置讀資料

RandomAccessFile raf = new RandomAccessFile(fileName, “r”); // r表示已只讀開啟

(15); // 從15開始讀

Int();

ine();

// 序列化物件

物件序列化,必須實現Serializable介面

// 儲存資料到磁碟

ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILENAME)));

eObject(serialObject);

e();

// 讀出資料

ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILENAME));

Object();

e();

// 讀寫Jar或Zip文件

ZipFile zippy = new ZipFile(“”);

Enumeration all = ies(); // 列舉值列出所有檔案清單

while (oreElements()) {

ZipEntry entry = (ZipEntry)Element();

if (le())

println(“Directory: ” + ame());

// 讀寫檔案

FileOutputStream os = new FileOutputStream(ame());

InputStream is = nputStream(entry);

int n = 0;

byte[] b = new byte[8092];

while ((n = (b)) > 0) {

e(b, 0, n);

e();

e();

}

}

// 讀寫gzip文件

FileInputStream fin = new FileInputStream(FILENAME);

GZIPInputStream gzis = new GZIPInputStream(fin);

InputStreamReader xover = new InputStreamReader(gzis);

BufferedReader is = new BufferedReader(xover);

String line;

while ((line = Line()) != null)

tln(“Read: ” + line);

標籤: JAVA 程式碼
  • 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-tw/itrz/dengji/mw2v6r.html