接著上一篇再為大家介紹java應(yīng)用和輸入輸出常用方法,供大家參考,具體內(nèi)容如下
一、應(yīng)用
1、使用StringBuilder或StringBuffer
// join(["a", "b", "c"]) -> "a and b and c"String join(List<String> strs) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : strs) { if (first) first = false; else sb.append(" and "); sb.append(s); } return sb.toString();}
2、生成一個范圍內(nèi)的隨機整數(shù)
Random rand = new Random(); // Between 1 and 6, inclusiveint diceRoll() { return rand.nextInt(6) + 1;}
3、使用Iterator.remove()
void filter(List<String> list) { for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) { String item = iter.next(); if (...) iter.remove(); }}
remove()方法作用在next()方法最近返回的條目上。每個條目只能使用一次remove()方法。
4、返轉(zhuǎn)字符串
String reverse(String s) { return new StringBuilder(s).reverse().toString();}
這個方法可能應(yīng)該加入Java標準庫。
5、啟動一條線程
下面的三個例子使用了不同的方式完成了同樣的事情。
實現(xiàn)Runnnable的方式:
void startAThread0() { new Thread(new MyRunnable()).start();} class MyRunnable implements Runnable { public void run() { ... }}
繼承Thread的方式:
void startAThread1() { new MyThread().start();} class MyThread extends Thread { public void run() { ... }}
匿名繼承Thread的方式:
void startAThread2() { new Thread() { public void run() { ... } }.start();}
不要直接調(diào)用run()方法。總是調(diào)用Thread.start()方法,這個方法會創(chuàng)建一條新的線程并使新建的線程調(diào)用run()。
6、使用try-finally
I/O流例子:
void writeStuff() throws IOException { OutputStream out = new FileOutputStream(...); try { out.write(...); } finally { out.close(); }}
鎖例子:
void doWithLock(Lock lock) { lock.acquire(); try { ... } finally { lock.release(); }}
二、輸入/輸出
1、從輸入流里讀取字節(jié)數(shù)據(jù)
InputStream in = (...);try { while (true) { int b = in.read(); if (b == -1) break; (... process b ...) }} finally { in.close();}
read()方法要么返回下一次從流里讀取的字節(jié)數(shù)(0到255,包括0和255),要么在達到流的末端時返回-1。
2、從輸入流里讀取塊數(shù)據(jù)
InputStream in = (...);try { byte[] buf = new byte[100]; while (true) { int n = in.read(buf); if (n == -1) break; (... process buf with offset=0 and length=n ...) }} finally { in.close();}
要記住的是,read()方法不一定會填滿整個buf,所以你必須在處理邏輯中考慮返回的長度。
3、從文件里讀取文本
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(...), "UTF-8"));try { while (true) { String line = in.readLine(); if (line == null) break; (... process line ...) }} finally { in.close();}
4、向文件里寫文本
PrintWriter out = new PrintWriter( new OutputStreamWriter(new FileOutputStream(...), "UTF-8"));try { out.print("Hello "); out.print(42); out.println(" world!");} finally { out.close();}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助。
新聞熱點
疑難解答