Java经典用法总结(二)
作者:lijiao 时间:2023-11-24 20:39:10
接着上一篇再为大家介绍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();
}
不要像这样使用重复的字符串连接:s += item ,因为它的时间效率是O(n^2)。
使用StringBuilder或者StringBuffer时,可以使用append()方法添加文本和使用toString()方法去获取连接起来的整个文本。
优先使用StringBuilder,因为它更快。StringBuffer的所有方法都是同步的,而你通常不需要同步的方法。
2、生成一个范围内的随机整数
Random rand = new Random();
// Between 1 and 6, inclusive
int diceRoll() {
return rand.nextInt(6) + 1;
}
总是使用Java API方法去生成一个整数范围内的随机数。
不要试图去使用 Math.abs(rand.nextInt()) % n 这些不确定的用法,因为它的结果是有偏差的。此外,它的结果值有可能是负数,比如当rand.nextInt() == Integer.MIN_VALUE时就会如此。
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();
}
}
如果try之前的语句运行失败并且抛出异常,那么finally语句块就不会执行。但无论怎样,在这个例子里不用担心资源的释放。
如果try语句块里面的语句抛出异常,那么程序的运行就会跳到finally语句块里执行尽可能多的语句,然后跳出这个方法(除非这个方法还有另一个外围的finally语句块)。
二、输入/输出
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();
}
BufferedReader对象的创建显得很冗长。这是因为Java把字节和字符当成两个不同的概念来看待(这与C语言不同)。
你可以使用任何类型的InputStream来代替FileInputStream,比如socket。
当达到流的末端时,BufferedReader.readLine()会返回null。
要一次读取一个字符,使用Reader.read()方法。
你可以使用其他的字符编码而不使用UTF-8,但最好不要这样做。
4、向文件里写文本
PrintWriter out = new PrintWriter(
new OutputStreamWriter(new FileOutputStream(...), "UTF-8"));
try {
out.print("Hello ");
out.print(42);
out.println(" world!");
} finally {
out.close();
}
Printwriter对象的创建显得很冗长。这是因为Java把字节和字符当成两个不同的概念来看待(这与C语言不同)。
就像System.out,你可以使用print()和println()打印多种类型的值。
你可以使用其他的字符编码而不使用UTF-8,但最好不要这样做。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于多网卡环境下Eureka服务注册IP的选择问题
![](https://img.aspxhome.com/file/2023/8/113388_0s.jpg)
Android四种数据存储的应用方式
基于jdk动态代理和cglib动态代理实现及区别说明
分享一个C#编写简单的聊天程序(详细介绍)
![](https://img.aspxhome.com/file/2023/3/119463_0s.gif)
c#多线程网络聊天程序代码分享(服务器端和客户端)
Android实现闪光灯效果
![](https://img.aspxhome.com/file/2023/1/137891_0s.jpg)
编写简易Android天气应用的代码示例
![](https://img.aspxhome.com/file/2023/7/139287_0s.jpg)
C# 动画窗体(AnimateWindow)的小例子
IDEA2020.2.3中创建JavaWeb工程的完整步骤记录
![](https://img.aspxhome.com/file/2023/5/110605_0s.png)
java实现文件拷贝的七种方式
Java虚拟机JVM性能优化(二):编译器
![](https://img.aspxhome.com/file/2023/6/115916_0s.jpg)
Java判断两个日期相差天数的方法
java开发AOP面向切面编程入门
![](https://img.aspxhome.com/file/2023/1/122951_0s.png)
Android实现计步器功能
My eclipse 端口占用(9360)问题解决办法
![](https://img.aspxhome.com/file/2023/2/68542_0s.png)
Qt TCP实现简单通信功能
![](https://img.aspxhome.com/file/2023/3/124023_0s.jpg)
Android混合开发教程之WebView的使用方法总结
![](https://img.aspxhome.com/file/2023/3/139503_0s.jpg)