pg电子游戏软件,类似车行168的软件,单机游戏内购破解平台,今日打牌财神方位查询老黄历

JAVA常用代碼積累

時(shí)間:2020-08-18 19:22:39 計(jì)算機(jī)等級(jí) 我要投稿

JAVA常用代碼積累

  Java是一個(gè)面向?qū)ο蟮恼Z言。對(duì)程序員來說,這意味著要注意應(yīng)中的數(shù)據(jù)和操縱數(shù)據(jù)的方法(method),而不是嚴(yán)格地用過程來思考。下面是小編整理的關(guān)于JAVA常用代碼積累,希望大家認(rèn)真閱讀!

  1.獲取環(huán)境變量

  System.getenv(“PATH”);

  System.getenv(“JAVA_HOME”);

  2.獲取系統(tǒng)屬性

  System.getProperty(“pencil color”); // 得到屬性值

  java -Dpencil color=green

  System.getProperty(“java.specification.version”); // 得到Java版本號(hào)

  Properties p = System.getProperties(); // 得到所有屬性值

  p.list(System.out);

  3.String Tokenizer

  // 能夠同時(shí)識(shí)別, 和 |

  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(); // 反轉(zhuǎn)字符串

  5. 數(shù)字

  // 數(shù)字與對(duì)象之間互相轉(zhuǎn)換 – Integer轉(zhuǎn)int

  Integer.intValue();

  // 浮點(diǎn)數(shù)的.舍入

  Math.round()

  // 數(shù)字格式化

  NumberFormat

  // 整數(shù) -> 二進(jìn)制字符串

  toBinaryString()或valueOf()

  // 整數(shù) -> 八進(jìn)制字符串

  toOctalString()

  // 整數(shù) -> 十六進(jìn)制字符串

  toHexString()

  // 數(shù)字格式化為羅馬數(shù)字

  RomanNumberFormat()

  // 隨機(jī)數(shù)

  Random r = new Random();

  r.nextDouble();

  r.nextInt();

  6. 日期和時(shí)間

  // 查看當(dāng)前日期

  Date today = new Date();

  Calendar.getInstance().getTime();

  // 格式化默認(rèn)區(qū)域日期輸出

  DateFormat df = DateFormat.getInstance();

  df.format(today);

  // 格式化制定區(qū)域日期輸出

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

  // 設(shè)置具體日期

  GregorianCalendar d1 = new GregorianCalendar(2009, 05, 06); // 6月6日

  GregorianCalendar d2 = new GregorianCalendar(); // 今天

  Calendar d3 = Calendar.getInstance(); // 今天

  d1.getTime(); // Calendar或GregorianCalendar轉(zhuǎn)成Date格式

  d3.set(Calendar.YEAR, 1999);

  d3.set(Calendar.MONTH, Calendar.APRIL);

  d3.set(Calendar.DAY_OF_MONTH, 12);

  // 字符串轉(zhuǎn)日期

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

  // 計(jì)算日期間隔(轉(zhuǎn)換成long來計(jì)算)

  today.getTime() – old.getTime();

  // 比較日期

  Date類型,就使用equals(), before(), after()來計(jì)算

  long類型,就使用==, <, >來計(jì)算

  // 第幾日

  使用Calendar的get()方法

  Calendar c = Calendar.getInstance();

  c.get(Calendar.YEAR);

  // 記錄耗時(shí)

  long start = System.currentTimeMillis();

  long end = System.currentTimeMillis();

  long elapsed = end – start;

  System.nanoTime(); //毫秒

  // 長整形轉(zhuǎn)換成秒

  Double.toString(t/1000D);

  7.結(jié)構(gòu)化數(shù)據(jù)

  // 數(shù)組拷貝

  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) // 返回指定位置的對(duì)象句柄

  indexOf(Object o) // 如果找到給定對(duì)象,則返回其索引值;否則,返回-1

  remove(Object o) // 根據(jù)引用刪除對(duì)象

  remove(int i) // 根據(jù)位置刪除對(duì)象

  toArray() // 返回包含集合對(duì)象的數(shù)組

  // 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 hm = new HashMap();

  hm.get(key); // 通過key得到value

  hm.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 – 與系統(tǒng)相關(guān)的用戶設(shè)置,類似名-值對(duì)

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

  // 用戶設(shè)置了新值,存儲(chǔ)回去

  prefs.put(“textFontName”, “new-bright”);

  prefs.put(“displayFontName”, “new-balckletter”);

  // Properties – 類似名-值對(duì),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. 數(shù)組:Arrays.sort(strings);

  2. List:Collections.sort(list);

  3. 自定義類:class SubComp implements Comparator

  然后使用Arrays.sort(strings, new SubComp())

  // 兩個(gè)接口

  1. java.lang.Comparable: 提供對(duì)象的自然排序,內(nèi)置于類中

  int compareTo(Object o);

  boolean equals(Object o2);

  2. java.util.Comparator: 提供特定的比較方法

  int compare(Object o1, Object o2)

  // 避免重復(fù)排序,可以使用TreeMap

  TreeMap sorted = new TreeMap(unsortedHashMap);

  // 排除重復(fù)元素

  Hashset hs – new HashSet();

  // 搜索對(duì)象

  binarySearch(): 快速查詢 – Arrays, Collections

  contains(): 線型搜索 – ArrayList, HashSet, Hashtable, linkedList, Properties, Vector

  containsKey(): 檢查集合對(duì)象是否包含給定 – HashMap, Hashtable, Properties, TreeMap

  containsValue(): 主鍵(或給定值) – HashMap, Hashtable, Properties, TreeMap

  indexOf(): 若找到給定對(duì)象,返回其位置 – ArrayList, linkedList, List, Stack, Vector

  search(): 線型搜素 – Stack

  // 集合轉(zhuǎn)數(shù)組

  toArray();

  // 集合總結(jié)

  Collection: Set – HashSet, TreeSet

  Collection: List – ArrayList, Vector, LinkedList

  Map: HashMap, HashTable, TreeMap

  8. 泛型與foreach

  // 泛型

  List myList = new ArrayList();

  // foreach

  for (String s : myList) {

  System.out.println(s);

  }

  9.面向?qū)ο?/strong>

  // 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) // 優(yōu)化

  return true;

  if (!(o instanceof EqualsDemo)) // 可投射到這個(gè)類

  return false;

  EqualsDemo other = (EqualsDemo)o; // 類型轉(zhuǎn)換

  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方法

  要克隆對(duì)象,必須先做兩步: 1. 覆蓋對(duì)象的clone()方法; 2. 實(shí)現(xiàn)空的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”);

  }

  });

  在調(diào)用System.exit(0);的時(shí)候,這兩個(gè)方法將被執(zhí)行

  // Singleton模式

  // 實(shí)現(xiàn)1

  public class MySingleton() {

  public static final MySingleton INSTANCE = new MySingleton();

  private MySingleton() {}

  }

  // 實(shí)現(xiàn)2

  public class MySingleton() {

  public static MySingleton instance = new MySingleton();

  private MySingleton() {}

  public static MySingleton getInstance() {

  return instance;

  }

  }

  // 自定義異常

  Exception: 編譯時(shí)檢查

  RuntimeException: 運(yùn)行時(shí)檢查

  public class MyException extends RuntimeException {

  public MyException() {

  super();

  }

  public MyException(String msg) {

  super(msg);

  }

  }

  10. 輸入和輸出

  // Stream, Reader, Writer

  Stream: 處理字節(jié)流

  Reader/Writer: 處理字符,通用Unicode

  // 從標(biāo)準(zhǔn)輸入設(shè)備讀數(shù)據(jù)

  1. 用System.in的BufferedInputStream()讀取字節(jié)

  int b = System.in.read();

  System.out.println(“Read data: ” + (char)b); // 強(qiáng)制轉(zhuǎn)換為字符

  2. BufferedReader讀取文本

  如果從Stream轉(zhuǎn)成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為整數(shù)

  }

  is.close();

  // 向標(biāo)準(zhǔn)輸出設(shè)備寫數(shù)據(jù)

  1. 用System.out的println()打印數(shù)據(jù)

  2. 用PrintWriter打印

  PrintWriter pw = new PrintWriter(System.out);

  pw.println(“The answer is ” + myAnswer + ” at this time.”);

  // Formatter類

  格式化打印內(nèi)容

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

  // 復(fù)制文件

  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;

  // 讀一個(gè)塊,如果有字符,加入緩沖區(qū)

  while ((n = is.read(b)) > 0) {

  sb.append(b, 0, n);

  }

  return sb.toString();

  // 重定向標(biāo)準(zhǔn)流

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

  // 讀取二進(jìn)制數(shù)據(jù)

  DataOutputStream os = new DataOutputStream(new FileOutputStream(“a.txt”));

  os.writeInt(i);

  os.writeDouble(d);

  os.close();

  // 從指定位置讀數(shù)據(jù)

  RandomAccessFile raf = new RandomAccessFile(fileName, “r”); // r表示已只讀打開

  raf.seek(15); // 從15開始讀

  raf.readInt();

  raf.radLine();

  // 串行化對(duì)象

  對(duì)象串行化,必須實(shí)現(xiàn)Serializable接口

  // 保存數(shù)據(jù)到磁盤

  ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILENAME)));

  os.writeObject(serialObject);

  os.close();

  // 讀出數(shù)據(jù)

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

【JAVA常用代碼積累】相關(guān)文章:

Java中的動(dòng)態(tài)代碼編程06-05

在Java中執(zhí)行JavaScript代碼11-18

Java代碼的基本知識(shí)06-02

如何讓JAVA代碼更高效10-06

Java定時(shí)器代碼的編寫10-05

java證書的加密與解密代碼05-24

常用HTML代碼解釋09-18

java非對(duì)稱加密的源代碼(rsa)11-14

關(guān)于Java源代碼折行的規(guī)則10-07

主站蜘蛛池模板: 铁岭市| 精河县| 军事| 上蔡县| 琼中| 万山特区| 八宿县| 土默特右旗| 青川县| 达拉特旗| 钟祥市| 桂平市| 凯里市| 黑水县| 应用必备| 赤城县| 福建省| 黄浦区| 石楼县| 朔州市| 策勒县| 鱼台县| 象州县| 泰和县| 七台河市| 襄垣县| 松潘县| 鹰潭市| 绥棱县| 精河县| 正阳县| 卢龙县| 宕昌县| 曲靖市| 怀远县| 德令哈市| 大埔区| 弋阳县| 精河县| 肇州县| 曲水县|