Most Frequently Used Java Code Fragments

 Hello World

import java.io.*;
 
public class GoodFrom {
    public static void main (String[] args) {
       System.out.println("Hello World");
    }
}
1. get environment variables

System.getenv("PATH");
System.getenv("JAVA_HOME");

// 2. Get the system property 

System.getProperty("pencil color"); // Get the 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

// Can recognize both, and | 

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

while (st.hasMoreElements()) {

st.nextToken();

}

// Treat the separator as a token 

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

// 4. StringBuffer (synchronized) and StringBuilder (non-synchronized) 

StringBuilder sb = new StringBuilder();

sb.append("Hello");

sb.append("World");

sb.toString();

new StringBuffer(a).reverse(); // Reverse the string

// 5. Numbers

// Convert between numbers and objects – Integer to int

Integer.intValue();

// rounding of floating point numbers

Math.round()

// number formatting

NumberFormat

// integer -> binary string

toBinaryString() or valueOf()

// integer -> octal string

toOctalString()

// integer -> hex string

toHexString()

// Numbers are formatted as Roman numerals

RomanNumberFormat()

// random number 

Random r = new Random();

r.nextDouble();

r.nextInt();

// 6. Date and time

// View the current date 

Date today = new Date();

Calendar.getInstance().getTime();

// Format the default locale date output 

DateFormat df = DateFormat.getInstance();

df.format(today);

// Format the date output in the designated area 

DateFormat df_cn = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);

String now = df_cn.format(today);

// Print the date in the required format 

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM- dd hh:mm:ss");

sdf.format(today);

// Set the specific date 

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

GregorianCalendar d2 = new GregorianCalendar(); // Today's 

Calendar d3 = Calendar.getInstance(); // Today's 

d1.getTime (); // Convert Calendar or GregorianCalendar to 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 addition and subtraction 

Date now = new Date();

long t = now.getTime();

t += 7002460601000 ;

Date then = new Date(t);

Calendar now = Calendar.getInstance();

now.add(Calendar.YEAR, -2 );

// Calculate date interval (convert to long to calculate)

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

// compare dates

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

For long type, use ==, <, > to calculate

// day of the day

Use Calendar's get() method

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

// Convert long integer to seconds 

Double.toString(t / 1000D);

// 7. Structured data

// Array copy 

System.arrayCopy(oldArray, 0, newArray, 0 , oldArray.length);

// ArrayList 

add(Object o) // Add 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 the given element, return the true value 

get( int i) // Return the object handle at the specified position 

indexOf(Object o) // If the given object is found, return its index value; otherwise, return -1 

remove( Object o) // remove objects by reference 

remove( int i) // remove objects by position 

toArray() // return an array containing collection objects

// Iterator 

List list = new ArrayList();

Iterator it = list.iterator();

while (it.hasNext())

Object o = it.next();

// LinkedList 

LinkedList list = new LinkedList();

ListIterator it = list.listIterator();

while (it.hasNext())

Object o = it.next();

// HashMap 

HashMap hm = new HashMap();

hm.get(key); // Get value by key

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

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

// Method 1: Get all key values 

​​Iterator 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, like 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 a new value and stores it back 

prefs.put("textFontName", " new - bright");

prefs.put("displayFontName", " new - balckletter");

// Properties - similar name-value pairs, between key and value, can be separated by "=", ":" or space, and annotated with "#" and "!" 

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

Arrays: Arrays.sort(strings);

List: Collections.sort(list);

Custom class: class SubComp implements Comparator

Then use Arrays.sort(strings, new SubComp())

// two interfaces

java.lang.Comparable: Provides natural ordering of objects, built into classes

int compareTo(Object o);

boolean equals(Object o2);

java.util.Comparator: provides specific comparison methods

int compare(Object o1, Object o2)

// To avoid repeated sorting, you can use TreeMap 

TreeMap sorted = new TreeMap(unsortedHashMap);

// Exclude duplicate elements 

Hashset hs - new HashSet();

// search object

binarySearch(): Quick Search – Arrays, Collections

contains(): Line Search – ArrayList, HashSet, Hashtable, linkedList, Properties, Vector

containsKey(): Checks if the collection object contains the given – HashMap, Hashtable, Properties, TreeMap

containsValue(): primary key (or given value) - HashMap, Hashtable, Properties, TreeMap

indexOf(): If the given object is found, return its position – ArrayList, linkedList, List, Stack, Vector

search(): Linear search – Stack

// collection to array

toArray();

// collection summary

Collection: Set – HashSet, TreeSet

Collection: List – ArrayList, Vector, LinkedList

Map: HashMap, HashTable, TreeMap

// 8. Generics and foreach

// Generic 

List myList = new ArrayList();

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

}

}

// Override equals method

public  boolean equals(Object o) {

if (o == this ) // optimize

return  true ;

if (!(o instanceof EqualsDemo)) // Can be cast to this class

return  false ;

EqualsDemo other = (EqualsDemo)o; // Type conversion

if (int1 != other.int1) // Compare by field

return  false ;

if (! obj1.equals(other.obj1))

return  false ;

return  true ;

}

// Override the hashcode method

private  volatile  int hashCode = 0; // Lazy initialization

public  int hashCode() {

if (hashCode == 0 ) {

int result = 17 ;

result = 37 * result + areaCode;

}

return hashCode;

}

// Clone method 

To clone an object, you must first do two steps: 1. Override the object's clone() method; 2. Implement the 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");

}

});

When calling System.exit( 0 );, these two methods will be executed

// 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 exception

Exception: compile time check

RuntimeException: runtime check

public  class MyException extends RuntimeException {

public MyException() {

super ();

}

public MyException(String msg) {

super (msg);

}

}

// 10. Input and output

// Stream, Reader, Writer

Stream: process byte streams

Reader / Writer: handles characters, generic Unicode

// read data from standard input device

Read bytes with System.in's BufferedInputStream()

int b = System.in.read();

System.out.println("Read data: " + ( char )b); // Force cast to character

BufferedReader reads text

If converting from Stream to Reader, use 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 device

Use System.out's println() to print data

Printing with PrintWriter

PrintWriter pw = new PrintWriter(System.out);

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

// Formatter class

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

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

// Copy file 

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

//The file is read into the string 

StringBuffer sb = new StringBuffer();

char [] b = new  char [8192 ];

int n;

// Read a block, if there are characters, add to the 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 text with different character sets 

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 the specified location 

RandomAccessFile raf = new RandomAccessFile(fileName, "r"); // r means read-only open 

raf.seek( 15); // Read from 15

raf.readInt();

raf.radLine();

// serialize the object

Object serialization must implement the Serializable interface

// Save data to disk 

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

os.writeObject(serialObject);

os.close();

// Read data 

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

is.readObject();

is.close();

// Read and write Jar or Zip documents 

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

Enumeration all = zippy.entries(); // The enumeration value lists all files

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 files 

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

2

Proudly powered by WordPress
Theme by anyway
Post a Comment (0)
Previous Post Next Post