接着上一篇再为大家介绍java应用和输入输出常用方法,供大家参考,具体内容如下
一、应用
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、生成一个范围内的随机整数
Random rand = new Random();
 
// Between 1 and 6, inclusive
int 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、返转字符串
String reverse(String s) {
 return new StringBuilder(s).reverse().toString();
}
这个方法可能应该加入Java标准库。
5、启动一条线程
下面的三个例子使用了不同的方式完成了同样的事情。
实现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();
}
不要直接调用run()方法。总是调用Thread.start()方法,这个方法会创建一条新的线程并使新建的线程调用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、从输入流里读取字节数据
InputStream in = (...);
try {
 while (true) {
 int b = in.read();
 if (b == -1)
  break;
 (... process b ...)
 }
} finally {
 in.close();
}
read()方法要么返回下一次从流里读取的字节数(0到255,包括0和255),要么在达到流的末端时返回-1。
2、从输入流里读取块数据
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();
}
以上就是本文的全部内容,希望对大家的学习有所帮助。
本文地址:https://www.stayed.cn/item/21921
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我