Java是一個面向對象的語言。對程序員來說,這意味着要注意應中的數據和操縱數據的`方法(method),而不是嚴格地用過程來思考。下面是小編整理的關於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
(key); // 通過key得到value
(“No1”, “Hexinyu”);
(“No2”, “Sean”);
// 方法1: 獲取全部鍵值
Iterator
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
// 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);