麥穗技術
屌絲程序員的自我對白
干貨來啦霹抛!JAVA常用代碼
目錄 技術文章2016年6月22日
1.獲取環(huán)境變量
System.getenv(“PATH”);
System.getenv(“JAVA_HOME”);
//2.獲取系統(tǒng)屬性
System.getProperty(“pencil color”); // 得到屬性值
java -Dpencil color=green
System.getProperty(“java.specification.version”); // 得到Java版本號
Properties p = System.getProperties(); // 得到所有屬性值
p.list(System.out);
//3.String Tokenizer
// 能夠同時識別, 和 |
StringTokenizer st = new StringTokenizer(“Hello, World|of|Java”, “, |”);
while (st.hasMoreElements()) {
st.nextToken();
}
// 把分隔符視為token
StringTokenizer st = new StringTokenizer(“Hello, World|of|Java”, “, |”, true);
//4.StringBuffer(同步)和StringBuilder(非同步)
StringBuilder sb = new StringBuilder();
sb.append(“Hello”);
sb.append(“World”);
sb.toString();
new StringBuffer(a).reverse(); // 反轉字符串
//5. 數字
// 數字與對象之間互相轉換 – Integer轉int
Integer.intValue();
// 浮點數的舍入
Math.round()
// 數字格式化
NumberFormat
// 整數 -> 二進制字符串
toBinaryString()或valueOf()
// 整數 -> 八進制字符串
toOctalString()
// 整數 -> 十六進制字符串
toHexString()
// 數字格式化為羅馬數字
RomanNumberFormat()
// 隨機數
Random r = new Random();
r.nextDouble();
r.nextInt();
//6. 日期和時間
// 查看當前日期
Date today = new Date();
Calendar.getInstance().getTime();
// 格式化默認區(qū)域日期輸出
DateFormat df = DateFormat.getInstance();
df.format(today);
// 格式化制定區(qū)域日期輸出
DateFormat df_cn = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);
String now = df_cn.format(today);
// 按要求格式打印日期
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
sdf.format(today);
// 設置具體日期
GregorianCalendar d1 = new GregorianCalendar(2009, 05, 06); // 6月6日
GregorianCalendar d2 = new GregorianCalendar(); // 今天
Calendar d3 = Calendar.getInstance(); // 今天
d1.getTime(); // Calendar或GregorianCalendar轉成Date格式
d3.set(Calendar.YEAR, 1999);
d3.set(Calendar.MONTH, Calendar.APRIL);
d3.set(Calendar.DAY_OF_MONTH, 12);
// 字符串轉日期
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
Date now = sdf.parse(String);
// 日期加減
Date now = new Date();
long t = now.getTime();
t += 7002460601000;
Date then = new Date(t);
Calendar now = Calendar.getInstance();
now.add(Calendar.YEAR, -2);
// 計算日期間隔(轉換成long來計算)
today.getTime() – old.getTime();
// 比較日期
Date類型椎扬,就使用equals(), before(), after()來計算
long類型,就使用==, <, >來計算
// 第幾日
使用Calendar的get()方法
Calendar c = Calendar.getInstance();
c.get(Calendar.YEAR);
// 記錄耗時
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
long elapsed = end – start;
System.nanoTime(); //毫秒
// 長整形轉換成秒
Double.toString(t/1000D);
//7.結構化數據
// 數組拷貝
System.arrayCopy(oldArray, 0, newArray, 0, oldArray.length);
// 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 = list.iterator();
while (it.hasNext())
Object o = it.next();
// 鏈表
LinkedList list = new LinkedList();
ListIterator it = list.listIterator();
while (it.hasNext())
Object o = it.next();
// HashMap
HashMap hm = new HashMap();
hm.get(key); // 通過key得到value
hm.put(“No1”, “Hexinyu”);
hm.put(“No2”, “Sean”);
// 方法1: 獲取全部鍵值
Iterator it = hm.values().iterator();
while (it.hasNext()) {
String myKey = it.next();
String myValue = hm.get(myKey);
}
// 方法2: 獲取全部鍵值
for (String key : hm.keySet()) {
String myKey = key;
String myValue = hm.get(myKey);
}
// Preferences – 與系統(tǒng)相關的用戶設置,類似名-值對
Preferences prefs = Preferences.userNodeForPackage(ArrayDemo.class);
String text = prefs.get(“textFontName”, “l(fā)ucida-bright”);
String display = prefs.get(“displayFontName”, “l(fā)ucida-balckletter”);
System.out.println(text);
System.out.println(display);
// 用戶設置了新值暑认,存儲回去
prefs.put(“textFontName”, “new-bright”);
prefs.put(“displayFontName”, “new-balckletter”);
// Properties – 類似名-值對困介,key和value之間,可以用”=”蘸际,”:”或空格分隔座哩,用”#”和”!”注釋
InputStream in = MediationServer.class.getClassLoader().getResourceAsStream(“msconfig.properties”);
Properties prop = new Properties();
prop.load(in);
in.close();
prop.setProperty(key, value);
prop.getProperty(key);
// 排序
數組:Arrays.sort(strings);
List:Collections.sort(list);
自定義類:class SubComp implements Comparator
然后使用Arrays.sort(strings, new SubComp())
// 兩個接口
- java.lang.Comparable: 提供對象的自然排序,內置于類中
int compareTo(Object o);
boolean equals(Object o2);
- java.util.Comparator: 提供特定的比較方法
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) {
System.out.println(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) {
System.out.println(new ToStringWith(43, 78));
}
}
// 覆蓋equals方法
public boolean equals(Object o) {
if (o == this) // 優(yōu)化
return true;
if (!(o instanceof EqualsDemo)) // 可投射到這個類
return false;
EqualsDemo other = (EqualsDemo)o; // 類型轉換
if (int1 != other.int1) // 按字段比較
return false;
if (!obj1.equals(other.obj1))
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. 實現(xiàn)空的Cloneable接口
public class Clone1 implements Cloneable {
public Object clone() {
return super.clone();
}
}
// Finalize方法
Object f = new Object() {
public void finalize() {
System.out.println(“Running finalize()”);
}
};
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println(“Running Shutdown Hook”);
}
});
在調用System.exit(0);的時候驾诈,這兩個方法將被執(zhí)行
// Singleton模式
// 實現(xiàn)1
public class MySingleton() {
public static final MySingleton INSTANCE = new MySingleton();
private MySingleton() {}
}
// 實現(xiàn)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: 處理字節(jié)流
Reader/Writer: 處理字符,通用Unicode
// 從標準輸入設備讀數據
- 用System.in的BufferedInputStream()讀取字節(jié)
int b = System.in.read();
System.out.println(“Read data: ” + (char)b); // 強制轉換為字符
- BufferedReader讀取文本
如果從Stream轉成Reader溶浴,使用InputStreamReader類
BufferedReader is = new BufferedReader(new
InputStreamReader(System.in));
String inputLine;
while ((inputLine = is.readLine()) != null) {
System.out.println(inputLine);
int val = Integer.parseInt(inputLine); // 如果inputLine為整數
}
is.close();
// 向標準輸出設備寫數據
用System.out的println()打印數據
用PrintWriter打印
PrintWriter pw = new PrintWriter(System.out);
pw.println(“The answer is ” + myAnswer + ” at this time.”);
// Formatter類
格式化打印內容
Formatter fmtr = new Formatter();
fmtr.format(“%1$04d – the year of %2$f”, 1951, Math.PI);
或者System.out.printf();或者System.out.format();
// 原始掃描
void doFile(Reader is) {
int c;
while ((c = is.read()) != -1) {
System.out.println((char)c);
}
}
// Scanner掃描
Scanner可以讀取File, InputStream, String, Readable
try {
Scanner scan = new Scanner(new File(“a.txt”));
while (scan.hasNext()) {
String s = scan.next();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 讀取文件
BufferedReader is = new BufferedReader(new FileReader(“myFile.txt”));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“bytes.bat”));
is.close();
bos.close();
// 復制文件
BufferedIutputStream is = new BufferedIutputStream(new FileIutputStream(“oldFile.txt”));
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(“newFile.txt”));
int b;
while ((b = is.read()) != -1) {
os.write(b);
}
is.close();
os.close();
// 文件讀入字符串
StringBuffer sb = new StringBuffer();
char[] b = new char[8192];
int n;
// 讀一個塊乍迄,如果有字符,加入緩沖區(qū)
while ((n = is.read(b)) > 0) {
sb.append(b, 0, n);
}
return sb.toString();
// 重定向標準流
String logfile = “error.log”;
System.setErr(new PrintStream(new FileOutputStream(logfile)));
// 讀寫不同字符集文本
BufferedReader chinese = new BufferedReader(new InputStreamReader(new FileInputStream(“chinese.txt”), “ISO8859_1”));
PrintWriter standard = new PrintWriter(new OutputStreamWriter(new FileOutputStream(“standard.txt”), “UTF-8”));
// 讀取二進制數據
DataOutputStream os = new DataOutputStream(new FileOutputStream(“a.txt”));
os.writeInt(i);
os.writeDouble(d);
os.close();
// 從指定位置讀數據
RandomAccessFile raf = new RandomAccessFile(fileName, “r”); // r表示已只讀打開
raf.seek(15); // 從15開始讀
raf.readInt();
raf.radLine();
// 串行化對象
對象串行化士败,必須實現(xiàn)Serializable接口
// 保存數據到磁盤
ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILENAME)));
os.writeObject(serialObject);
os.close();
// 讀出數據
ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILENAME));
is.readObject();
is.close();
// 讀寫Jar或Zip文檔
ZipFile zippy = new ZipFile(“a.jar”);
Enumeration all = zippy.entries(); // 枚舉值列出所有文件清單
while (all.hasMoreElements()) {
ZipEntry entry = (ZipEntry)all.nextElement();
if (entry.isFile())
println(“Directory: ” + entry.getName());
// 讀寫文件
FileOutputStream os = new FileOutputStream(entry.getName());
InputStream is = zippy.getInputStream(entry);
int n = 0;
byte[] b = new byte[8092];
while ((n = is.read(b)) > 0) {
os.write(b, 0, n);
is.close();
os.close();
}
}
// 讀寫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 = is.readLine()) != null)
System.out.println(“Read: ” + line);
2
Proudly powered by WordPress
Theme by anyway
7
流量商城
【歐洲杯】賽程比分
余額查詢
簽到設置