獻禮了~~Java常用代碼一筐打盡

來源:互聯網
上載者:User

標籤:字元   oid   儲存資料   set   property   泛型   date類   lang   運行時   

1.擷取環境變數


System.getenv(“PATH”);


System.getenv(“JAVA_HOME”);


//2.擷取系統屬性


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();


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


DateFormat df = DateFormat.getInstance();


df.format(today);


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


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 += 700*24*60*60*1000;


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<String, String> hm = new HashMap<String, String>();


hm.get(key); // 通過key得到value


hm.put(“No1”, “Hexinyu”);


hm.put(“No2”, “Sean”);


// 方法1: 擷取全部索引值


Iterator<String> 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 – 與系統相關的使用者佈建,類似名-值對


Preferences prefs = Preferences.userNodeForPackage(ArrayDemo.class);


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


String display = prefs.get(“displayFontName”, “lucida-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);


// 排序


1. 數組:Arrays.sort(strings);


2. List:Collections.sort(list);


3. 自訂類:class SubComp implements Comparator


然後使用Arrays.sort(strings, new SubComp())


// 兩個介面


1. java.lang.Comparable: 提供對象的自然排序,內建於類中


int compareTo(Object o);


boolean equals(Object o2);


2. 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<String> myList = new ArrayList<String>();


// 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) // 最佳化


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. 實現空的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);的時候,這兩個方法將被執行


// 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. 用System.in的BufferedInputStream()讀取位元組


int b = System.in.read();


System.out.println(“Read data: ” + (char)b); // 強制轉換為字元


2. 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();


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


1. 用System.out的println()列印資料


2. 用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;


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


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();


// 序列化對象


對象序列化,必須實現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);

 

社區源碼下載:http://www.jinhusns.com/Products/Download/?type=yhq

獻禮了~~Java常用代碼一筐打盡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.