It's a tribute. ~~java common code a basket hit

Source: Internet
Author: User
Tags date now dateformat object serialization stringbuffer

1. Get Environment variables


System.getenv ("PATH");


System.getenv ("Java_home");


2. Get System Properties


System.getproperty ("Pencil Color"); Get property value


Java-dpencil Color=green


System.getproperty ("Java.specification.version"); Get the Java version number


Properties p = system.getproperties (); Get all property values


P.list (System.out);


3.String Tokenizer


Ability to identify, and |


StringTokenizer st = new StringTokenizer ("Hello, world|of| Java ",", | ");


while (St.hasmoreelements ()) {


St.nexttoken ();


}


Treat the delimiter as token


StringTokenizer st = new StringTokenizer ("Hello, world|of| Java ",", | ", true);


4.StringBuffer (synchronous) and StringBuilder (non-synchronous)


StringBuilder sb = new StringBuilder ();


Sb.append ("Hello");


Sb.append ("World");


Sb.tostring ();


New StringBuffer (a). reverse (); Invert string


5. Digital


Convert between numbers and objects –integer to int


Integer.intvalue ();


Rounding of floating-point numbers


Math.Round ()


Digital formatting


NumberFormat


Integer---binary string


Tobinarystring () or valueof ()


Octal string, Integer


Tooctalstring ()


hexadecimal string, Integer


Tohexstring ()


Numbers formatted as Roman numerals


Romannumberformat ()


Random number


Random r = new Random ();


R.nextdouble ();


R.nextint ();


6. Date and time


View current date


Date today = new Date ();


Calendar.getinstance (). GetTime ();


Formatting the default zone date output


DateFormat df = dateformat.getinstance ();


Df.format (today);


Format to set the date output of the region


DateFormat DF_CN = dateformat.getdateinstance (Dateformat.full, Locale.china);


String now = Df_cn.format (today);


Print dates as required


SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");


Sdf.format (today);


Set a specific date


GregorianCalendar D1 = new GregorianCalendar (2009, 05, 06); June 6


GregorianCalendar D2 = new GregorianCalendar (); Today


Calendar d3 = Calendar.getinstance (); Today


D1.gettime (); Calendar or GregorianCalendar turns into date format


D3.set (Calendar.year, 1999);


D3.set (Calendar.month, Calendar.april);


D3.set (Calendar.day_of_month, 12);


String to date


SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");


Date now = Sdf.parse (String);


Date plus minus


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


Calculate date interval (converted to long to calculate)


Today.gettime () –old.gettime ();


Compare dates


Date type, use Equals (), before (), after () to calculate


Long type, use = =, <, > to calculate


Day of the Week


Use the Get () method of the calendar


Calendar C = calendar.getinstance ();


C.get (calendar.year);


Record time


Long start = System.currenttimemillis ();


Long end = System.currenttimemillis ();


long elapsed = End–start;


System.nanotime (); Milliseconds


Long shaping translates into seconds


Double.tostring (t/1000d);


7. Structured data


Array copy


System.arraycopy (Oldarray, 0, NewArray, 0, oldarray.length);


ArrayList


Add (Object O)//Adds the given element at the end


Add (int i, Object o)//Insert the given element at the specified position


Clear ()//Remove all elements from the collection


Contains (Object o)//If the vector contains a given element, returns the truth


Get (int i)//returns the object handle at the specified position


IndexOf (object o)//returns the index value of the given object if it is found; otherwise, 1


Remove (object o)//delete object by reference


Remove (int i)//delete objects by location


ToArray ()//Returns an array containing the collection object


Iterator


List List = new ArrayList ();


Iterator it = List.iterator ();


while (It.hasnext ())


Object o = It.next ();


Linked list


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); Get Value by key


Hm.put ("No1", "Hexinyu");


Hm.put ("No2", "Sean");


Method 1: Get all key values


Iterator<string> it = hm.values (). Iterator ();


while (It.hasnext ()) {


String MyKey = It.next ();


String myvalue = Hm.get (MyKey);


}


Method 2: Get all key values


For (String Key:hm.keySet ()) {


String MyKey = key;


String myvalue = Hm.get (MyKey);


}


preferences– system-related user settings, similar to name-value pairs


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


The user sets the new value and stores it back


Prefs.put ("Textfontname", "new-bright");


Prefs.put ("Displayfontname", "New-balckletter");


properties– similar to the name-value pair, between key and value, can be separated by "=", ":" or a Space, with "#" and "!" Comments


InputStream in = MediationServer.class.getClassLoader (). getResourceAsStream ("msconfig.properties");


Properties prop = new properties ();


Prop.load (in);


In.close ();


Prop.setproperty (key, value);


Prop.getproperty (key);


Sort


1. Array: Arrays.sort (strings);


2. List:Collections.sort (List);


3. Custom class: Class Subcomp implements Comparator


Then use Arrays.sort (strings, New Subcomp ())


Two interfaces


1. Java.lang.Comparable: Provides a natural ordering of objects, built into classes


int CompareTo (Object o);


Boolean equals (Object O2);


2. Java.util.Comparator: Provide a specific comparison method


int compare (object O1, Object O2)


Avoid repeating sorting, you can use TreeMap


TreeMap sorted = new TreeMap (UNSORTEDHASHMAP);


Exclude duplicate elements


Hashset hs–new Hashset ();


Search for objects


BinarySearch (): Quick query –arrays, collections


Contains (): Line Search –arraylist, HashSet, Hashtable, LinkedList, Properties, Vector


ContainsKey (): Checks whether the collection object contains a given –hashmap, Hashtable, Properties, TreeMap


Containsvalue (): Primary key (or given value) –hashmap, Hashtable, Properties, TreeMap


IndexOf (): If a given object is found, return its position –arraylist, LinkedList, List, Stack, Vector


Search (): Linear search –stack


Set-to-go array


ToArray ();


Collection Summary


Collection:set–hashset, TreeSet


Collection:list–arraylist, Vector, LinkedList


Map:hashmap, HashTable, TreeMap


8. Generics and foreach


Generic type


list<string> myList = new arraylist<string> ();


Foreach


for (String s:mylist) {


System.out.println (s);


}


9. Object-Oriented


ToString () formatting


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


}


}


Overriding the Equals method


public boolean equals (Object o) {


if (o = = this)//optimize


return true;


if (! ( o instanceof Equalsdemo)//Can be projected into this class


return false;


Equalsdemo other = (Equalsdemo) o; Type conversions


if (int1! = other.int1)//By field comparison


return false;


if (!obj1.equals (OTHER.OBJ1))


return false;


return true;


}


Overriding the Hashcode method


private volatile int hashcode = 0; Deferred initialization


public int hashcode () {


if (hashcode = = 0) {


int result = 17;


result = PNS * result + AreaCode;


}


return hashcode;


}


Clone method


To clone an object, you must first do two steps: 1. The Clone () method of the overlay object; 2. Implement an empty Cloneable interface


public class Clone1 implements cloneable {


Public Object Clone () {


return Super.clone ();


}


}


Finalize method


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


}


});


The two methods will be executed when calling System.exit (0);


Singleton mode


Implementation 1


public class Mysingleton () {


public static final Mysingleton INSTANCE = new Mysingleton ();


Private Mysingleton () {}


}


Implementation 2


public class Mysingleton () {


public static Mysingleton instance = new Mysingleton ();


Private Mysingleton () {}


public static Mysingleton getinstance () {


return instance;


}


}


Custom exceptions


Exception: Compile-time check


RuntimeException: Run-time check


public class MyException extends RuntimeException {


Public MyException () {


Super ();


}


Public myexception (String msg) {


Super (MSG);


}


}


10. Input and output


Stream, Reader, Writer


Stream: Processing byte stream


Reader/writer: Handling characters, Universal Unicode


Reading data from a standard input device


1. Read bytes with System.in's Bufferedinputstream ()


int b = System.in.read ();


System.out.println ("Read Data:" + (char) b); Cast to character


2. BufferedReader reading text


If you are transferring from stream to reader, use the InputStreamReader class


BufferedReader is = new BufferedReader (new


InputStreamReader (system.in));


String Inputline;


while ((Inputline = Is.readline ()) = null) {


System.out.println (Inputline);


int val = integer.parseint (inputline); If Inputline is an integer


}


Is.close ();


Write data to standard output devices


1. Print data using System.out's println ()


2. Print with PrintWriter


PrintWriter pw = new PrintWriter (System.out);


Pw.println ("The answer is" + Myanswer + "at this time.");


Formatter class


Format the content of the print


Formatter fmtr = new Formatter ();


Fmtr.format ("%1$04d–the Year of%2$f", 1951, Math.PI);


or System.out.printf (); or System.out.format ();


Original scan


void Dofile (Reader is) {


int C;


while ((c = Is.read ())! =-1) {


System.out.println ((char) c);


}


}


Scanner Scan


Scanner can read 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 ();


}


}


Read file


BufferedReader is = new BufferedReader (New FileReader ("MyFile.txt"));


Bufferedoutputstream BOS = new Bufferedoutputstream (New FileOutputStream ("Bytes.bat"));


Is.close ();


Bos.close ();


Copying files


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


File read-in string


StringBuffer sb = new StringBuffer ();


Char[] B = new char[8192];


int n;


Read a block, if there are characters, add buffer


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


Sb.append (b, 0, N);


}


return sb.tostring ();


REDIRECT Standard stream


String logfile = "Error.log";


System.seterr (New PrintStream (New FileOutputStream (logfile)));


Read and write different character set literals


BufferedReader Chinese = new BufferedReader (new InputStreamReader (New FileInputStream ("Chinese.txt"), "iso8859_1"));


PrintWriter standard = new PrintWriter (new OutputStreamWriter (New FileOutputStream ("Standard.txt"), "UTF-8");


Read binary data


DataOutputStream OS = new DataOutputStream (New FileOutputStream ("A.txt"));


Os.writeint (i);


Os.writedouble (d);


Os.close ();


Read data from a specified location


Randomaccessfile RAF = new Randomaccessfile (FileName, "R"); R indicates read-only open


Raf.seek (15); Read starting from 15


Raf.readint ();


Raf.radline ();


Serialization objects


Object serialization, the serializable interface must be implemented


Save data to disk


ObjectOutputStream OS = new ObjectOutputStream (new Bufferedoutputstream (New FileOutputStream (FILENAME));


Os.writeobject (Serialobject);


Os.close ();


Read the data


ObjectInputStream is = new ObjectInputStream (new FileInputStream (FILENAME));


Is.readobject ();


Is.close ();


Read or write a jar or zip document


ZipFile zippy = new ZipFile ("A.jar");


Enumeration all = Zippy.entries (); Enumeration values list all file lists


while (All.hasmoreelements ()) {


ZipEntry entry = (zipentry) all.nextelement ();


if (Entry.isfile ())


println ("Directory:" + entry.getname ());


Read and write files


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


}


}


Read and write gzip documentation


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

Community Source Download: HTTP://WWW.JINHUSNS.COM/PRODUCTS/DOWNLOAD/?TYPE=YHQ

It's a tribute. ~~java common code a basket hit

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.