Java 6+

Versions

Java SE 9 = 53 (0x35 hex),
Java SE 8 = 52 (0x34 hex),
Java SE 7 = 51 (0x33 hex),
Java SE 6.0 = 50 (0x32 hex),
Java SE 5.0 = 49 (0x31 hex),
JDK 1.4 = 48 (0x30 hex),
JDK 1.3 = 47 (0x2F hex),
JDK 1.2 = 46 (0x2E hex),
JDK 1.1 = 45 (0x2D hex).

Find class version

javap -verbose ClassName.class | findstr /R /C:"version"

Strings

String.format

String.format("Hello %s!", "world");     // Outputs "Hello world!"
String.format("Response code: %d", 200); // Outputs "Response code: 200"
String.format("%.2f", 0.1111);           // Outputs "0.11"

URL Encoding

Encode

String encoded = URLEncoder.encode("your string", "UTF-8");

Base 64 Encoding

Decode

String decoded = new String(Base64.getDecoder().decode("SGVsbG8gd29ybGQh"))

Store a stacktrace into a String

public String getStackTrace(Exception e) {
   StringWriter stackTrace = new StringWriter();
   e.printStackTrace(new PrintWriter(stackTrace));
   return stackTrace.toString();
}

Numbers

Random number between alpha and beta (included)

return ThreadLocalRandom.current().nextInt(alpha, beta + 1);

Files

Backup a file

if (persistenceFile.exists()) {
	Files.copy(persistenceFile.toPath(), Paths.get(persistenceFile + ".bak." + new Date().getTime()));
}

Change file dates

Java 5

file.setLastModifiedDate(date); // java.io.File + java.util.Date

Java 7

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileTime;
import java.util.Date;
 
Path path = ...;
Date modificationDate = ...;
Date accessDate = ...;
Date creationDate= ...;
FileTime modificationTime = FileTime.fromMillis(modificationDate.getTime());
FileTime accessTime = FileTime.fromMillis(accessDate.getTime());
FileTime creationTime = FileTime.fromMillis(creationDate.getTime());
BasicFileAttributeView attributes = Files.getFileAttributeView(location, BasicFileAttributeView.class);
attributes.setTimes(modificationTime, accessTime, creationTime);

Read a text file line by line

try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) {
   String line;
   while ((line = br.readLine()) != null) {
      // Do something
   }
} catch (Exception e) {
   // Do something
}

Persist an object to/from a file

public void persist(File file) throws IOException {
	try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
		oos.writeObject(this);
	}
}
 
public static PersistentCookieStore restore(File file) throws IOException, ClassNotFoundException {
	try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) {
		return (PersistentCookieStore) ois.readObject();
	}
}

Create multiple folders at one

new File("path/directory").mkdirs();

It creates “path/” and “path/directory/”

Access a config file in the resources folder

InputStream configStream = MyClass.class.getResourceAsStream("/my_config.properties");

Data structures

Concurrent set

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

Pair

Pair.java
public class Pair<T, U> {
 
	private T left;
	private U right;
 
	public Pair(T left, U right) {
		this.left = left;
		this.right = right;
	}
 
	public U getRight() {
		return right;
	}
 
	public void setRight(U right) {
		this.right = right;
	}
 
	public T getLeft() {
		return left;
	}
 
	public void setLeft(T left) {
		this.left = left;
	}
 
}

Date and time

Measure a duration

long startTime = System.nanoTime();    
// ... the code being measured ...    
long duration = System.nanoTime() - startTime; // [in nanoseconds. Divide by 1'000'000'000 to get seconds]

Date formats

DateFormat SWISS_DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); // 15.12.2013 23:59:44
DateFormat AMERICAN_DATE_FORMAT = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); // Fri May 09 20:49:44 CEST 2014

WARNING: THOSE OBJECTS ARE NOT THREAD-SAFE !!!!

Network

HTTP

Keep cookies

To keep cookies among multiple HttpURLConnection objects, use :

CookieManager cookieManager = new CookieManager();  
CookieHandler.setDefault(cookieManager);

The code can be found here.

POST

String urlParameters = "email=" + urlEncode(username) + "&pass=" + urlEncode(new String(Base64.getDecoder().decode(password)));
 
HttpURLConnection connection = null;
try {
	connection = (HttpURLConnection) FACEBOOK_LOGIN_URL.openConnection();
	connection.setRequestMethod("POST");
	connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
	connection.setRequestProperty("Content-Language", "en-US");
	connection.setUseCaches(false);
	connection.setDoOutput(true);
 
	DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
	wr.writeBytes(urlParameters);
	wr.close();
 
	LOGGER.info(String.format("Response code: %d", connection.getResponseCode()));
 
	InputStream is = connection.getInputStream();
	BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	StringBuilder response = new StringBuilder();
	String line;
	while((line = rd.readLine()) != null) {
	  response.append(line);
	  response.append('\r');
	}
	rd.close();
	LOGGER.info(response.toString());
	return true;
} catch (Exception e) {
	LOGGER.error("Error while logging to Facebook!", e);
	return false;
}

GET

private String getRequest(URL url) {
	HttpURLConnection connection = null;
	try {
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Content-Language", "en-US");
		connection.setUseCaches(false);
 
		LOGGER.debug(String.format("Response code: %d", connection.getResponseCode()));
 
		InputStream is = connection.getInputStream();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		StringBuilder response = new StringBuilder();
		String line;
		while((line = rd.readLine()) != null) {
		  response.append(line);
		  response.append('\r');
		}
		rd.close();
		return response.toString();
	} catch (Exception e) {
		LOGGER.error("Error while running GET request", e);
		return null;
	}
}

UI

Prompt for a value

String name = JOptionPane.showInputDialog("Enter your name: "); // javax.swing.JOptionPane

Running and building

System property

You can give parameters to the JVM

java ch.frattino.App -Dparam=value

And you can then read them from the app :

String value = System.getProperty("param"); // null if no parameter

Tools

Profile application

Win + R, jvisualvm.

This tool comes out-of-the-box with the JDK.

Eclipse

Prevent "Run" of .xml files

Preferences -> Run/Debug -> Launching --> [X] Always launch the previously launched application

Ignore packages during auto-complete

Preferences -> Java -> Appearance -> Type Filters

e.g.: java.awt.*

Print/export