JAVA常用代码

来源:互联网 发布:知我无情有情歌词 编辑:程序博客网 时间:2024/06/15 15:23

1.获取环境变量

System.getenv(“PATH”);System.getenv(“JAVA_HOME”);

2.获取系统属性

System.getProperty(“pencil color”); // 得到属性值java -Dpencil color=greenSystem.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();// 把分隔符视为tokenStringTokenizer 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转intInteger.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);// ArrayListadd(Object o) // 在末尾添加给定元素add(int i, Object o) // 在指定位置插入给定元素clear() // 从集合中删除全部元素Contains(Object o) // 如果Vector包含给定元素,返回真值get(int i) // 返回指定位置的对象句柄indexOf(Object o) // 如果找到给定对象,则返回其索引值;否则,返回-1remove(Object o) // 根据引用删除对象remove(int i) // 根据位置删除对象toArray() // 返回包含集合对象的数组// IteratorList 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();// HashMapHashMap hm = new HashMap();hm.get(key); // 通过key得到valuehm.put(“No1”, “Hexinyu”);hm.put(“No2”, “Sean”);// 方法1: 获取全部键值Iterator 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)// 避免重复排序,可以使用TreeMapTreeMap sorted = new TreeMap(unsortedHashMap);// 排除重复元素Hashset hs – new HashSet();// 搜索对象binarySearch():     快速查询 – Arrays, Collectionscontains():         线型搜索 – ArrayList, HashSet, Hashtable, linkedList, Properties, VectorcontainsKey():      检查集合对象是否包含给定 – HashMap, Hashtable, Properties, TreeMapcontainsValue():    主键(或给定值) – HashMap, Hashtable, Properties, TreeMapindexOf():          若找到给定对象,返回其位置 – ArrayList, linkedList, List, Stack, Vectorsearch():           线型搜素 – Stack// 集合转数组toArray();// 集合总结Collection: Set – HashSet, TreeSetCollection: List – ArrayList, Vector, LinkedListMap: HashMap, HashTable, TreeMap

8. 泛型与foreach

// 泛型List myList = new ArrayList();// foreachfor (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模式// 实现1public class MySingleton() {public static final MySingleton INSTANCE = new MySingleton();private MySingleton() {}// 实现2public 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, WriterStream:         处理字节流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, Readabletry {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 0
原创粉丝点击