JAVA常用代码积累
Java是一个面向对象的语言。对程序员来说,这意味着要注意应中的数据和操纵数据的`方法(method),而不是严格地用过程来思考。下面是小编整理的关于JAVA常用代码积累,希望大家认真阅读!
1.获取环境变量
nv(“PATH”);
nv(“JAVA_HOME”);
2.获取系统属性
roperty(“pencil color”); // 得到属性值
java -Dpencil color=green
roperty(“ion”); // 得到Java版本号
Properties p = roperties(); // 得到所有属性值
();
ng Tokenizer
// 能够同时识别, 和 |
StringTokenizer st = new StringTokenizer(“Hello, World|of|Java”, “, |”);
while (oreElements()) {
Token();
}
// 把分隔符视为token
StringTokenizer st = new StringTokenizer(“Hello, World|of|Java”, “, |”, true);
ngBuffer(同步)和StringBuilder(非同步)
StringBuilder sb = new StringBuilder();
nd(“Hello”);
nd(“World”);
ring();
new StringBuffer(a)rse(); // 反转字符串
5. 数字
// 数字与对象之间互相转换 – Integer转int
alue();
// 浮点数的舍入
d()
// 数字格式化
NumberFormat
// 整数 -> 二进制字符串
toBinaryString()或valueOf()
// 整数 -> 八进制字符串
toOctalString()
// 整数 -> 十六进制字符串
toHexString()
// 数字格式化为罗马数字
RomanNumberFormat()
// 随机数
Random r = new Random();
Double();
Int();
6. 日期和时间
// 查看当前日期
Date today = new Date();
nstance()ime();
// 格式化默认区域日期输出
DateFormat df = nstance();
at(today);
// 格式化制定区域日期输出
DateFormat df_cn = ateInstance(, A);
String now = df_at(today);
// 按要求格式打印日期
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
at(today);
// 设置具体日期
GregorianCalendar d1 = new GregorianCalendar(2009, 05, 06); // 6月6日
GregorianCalendar d2 = new GregorianCalendar(); // 今天
Calendar d3 = nstance(); // 今天
ime(); // Calendar或GregorianCalendar转成Date格式
(, 1999);
(H, L);
(_OF_MONTH, 12);
// 字符串转日期
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
Date now = e(String);
// 日期加减
Date now = new Date();
long t = ime();
t += 700*24*60*60*1000;
Date then = new Date(t);
Calendar now = nstance();
(, -2);
// 计算日期间隔(转换成long来计算)
ime() – ime();
// 比较日期
Date类型,就使用equals(), before(), after()来计算
long类型,就使用==, <, >来计算
// 第几日
使用Calendar的get()方法
Calendar c = nstance();
();
// 记录耗时
long start = entTimeMillis();
long end = entTimeMillis();
long elapsed = end – start;
Time(); //毫秒
// 长整形转换成秒
ring(t/1000D);
7.结构化数据
// 数组拷贝
yCopy(oldArray, 0, newArray, 0, th);
// 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 = ator();
while (ext())
Object o = ();
// 链表
LinkedList list = new LinkedList();
ListIterator it = Iterator();
while (ext())
Object o = ();
// HashMap
HashMap
(key); // 通过key得到value
(“No1”, “Hexinyu”);
(“No2”, “Sean”);
// 方法1: 获取全部键值
Iterator
while (ext()) {
String myKey = ();
String myValue = (myKey);
}
// 方法2: 获取全部键值
for (String key : et()) {
String myKey = key;
String myValue = (myKey);
}
// Preferences – 与系统相关的用户设置,类似名-值对
Preferences prefs = NodeForPackage(s);
String text = (“textFontName”, “lucida-bright”);
String display = (“displayFontName”, “lucida-balckletter”);
tln(text);
tln(display);
// 用户设置了新值,存储回去
(“textFontName”, “new-bright”);
(“displayFontName”, “new-balckletter”);
// Properties – 类似名-值对,key和value之间,可以用”=”,”:”或空格分隔,用”#”和”!”注释
InputStream in = lassLoader()esourceAsStream(“erties”);
Properties prop = new Properties();
(in);
e();
roperty(key, value);
roperty(key);
// 排序
1. 数组:(strings);
2. List:(list);
3. 自定义类:class SubComp implements Comparator
然后使用(strings, new SubComp())
// 两个接口
1. arable: 提供对象的自然排序,内置于类中
int compareTo(Object o);
boolean equals(Object o2);
2. arator: 提供特定的比较方法
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
// foreach
for (String s : myList) {
tln(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) {
tln(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 != 1) // 按字段比较
return false;
if (!ls(1))
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 e();
}
}
// Finalize方法
Object f = new Object() {
public void finalize() {
tln(“Running finalize()”);
}
};
untime()hutdownHook(new Thread() {
public void run() {
tln(“Running Shutdown Hook”);
}
});
在调用(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. 用的BufferedInputStream()读取字节
int b = ();
tln(“Read data: ” + (char)b); // 强制转换为字符
2. BufferedReader读取文本
如果从Stream转成Reader,使用InputStreamReader类
BufferedReader is = new BufferedReader(new
InputStreamReader());
String inputLine;
while ((inputLine = Line()) != null) {
tln(inputLine);
int val = eInt(inputLine); // 如果inputLine为整数
}
e();
// 向标准输出设备写数据
1. 用的println()打印数据
2. 用PrintWriter打印
PrintWriter pw = new PrintWriter();
tln(“The answer is ” + myAnswer + ” at this time.”);
// Formatter类
格式化打印内容
Formatter fmtr = new Formatter();
at(“%1$04d – the year of %2$f”, 1951, );
或者tf();或者at();
// 原始扫描
void doFile(Reader is) {
int c;
while ((c = ()) != -1) {
tln((char)c);
}
}
// Scanner扫描
Scanner可以读取File, InputStream, String, Readable
try {
Scanner scan = new Scanner(new File(“”));
while (ext()) {
String s = ();
}
} catch (FileNotFoundException e) {
tStackTrace();
}
}
// 读取文件
BufferedReader is = new BufferedReader(new FileReader(“”));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“”));
e();
e();
// 复制文件
BufferedIutputStream is = new BufferedIutputStream(new FileIutputStream(“”));
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(“”));
int b;
while ((b = ()) != -1) {
e(b);
}
e();
e();
// 文件读入字符串
StringBuffer sb = new StringBuffer();
char[] b = new char[8192];
int n;
// 读一个块,如果有字符,加入缓冲区
while ((n = (b)) > 0) {
nd(b, 0, n);
}
return ring();
// 重定向标准流
String logfile = “”;
rr(new PrintStream(new FileOutputStream(logfile)));
// 读写不同字符集文本
BufferedReader chinese = new BufferedReader(new InputStreamReader(new FileInputStream(“”), “ISO8859_1”));
PrintWriter standard = new PrintWriter(new OutputStreamWriter(new FileOutputStream(“”), “UTF-8”));
// 读取二进制数据
DataOutputStream os = new DataOutputStream(new FileOutputStream(“”));
eInt(i);
eDouble(d);
e();
// 从指定位置读数据
RandomAccessFile raf = new RandomAccessFile(fileName, “r”); // r表示已只读打开
(15); // 从15开始读
Int();
ine();
// 串行化对象
对象串行化,必须实现Serializable接口
// 保存数据到磁盘
ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILENAME)));
eObject(serialObject);
e();
// 读出数据
ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILENAME));
Object();
e();
// 读写Jar或Zip文档
ZipFile zippy = new ZipFile(“”);
Enumeration all = ies(); // 枚举值列出所有文件清单
while (oreElements()) {
ZipEntry entry = (ZipEntry)Element();
if (le())
println(“Directory: ” + ame());
// 读写文件
FileOutputStream os = new FileOutputStream(ame());
InputStream is = nputStream(entry);
int n = 0;
byte[] b = new byte[8092];
while ((n = (b)) > 0) {
e(b, 0, n);
e();
e();
}
}
// 读写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 = Line()) != null)
tln(“Read: ” + line);