JAVA常用代码。干货来啦!

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

0 Top


Proudly powered by WordPress
Theme by anyway

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值