Java Quick Reference - qyjohn/Hands-on-Linux GitHub Wiki
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.io.Console;
// Read and write a byte
FileInputStream in = new FileInputStream("in.txt");
FileOutputStream out = new FileOutputStream("out.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
in.close();
out.close();
// Read and write a char
FileReader in = new FileReader("in.txt");;
FileWriter out = new FileWriter("out.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
in.close();
out.close();
// Read and write a line
BufferedReader in = new BufferedReader(new FileReader("in.txt"));
PrintWriter out = new PrintWriter(new FileWriter("out.txt"));
String l;
while ((l = inputStream.readLine()) != null)
{
out.println(l);
}
in.close();
out.close();
// Scanner creates tokens from text
Scanner s = new Scanner(new BufferedReader(new FileReader("in.txt")));
while (s.hasNext())
{
System.out.println(s.next());
}
s.close();
// Reading from console
Console c = System.console();
String user = c.readLine("Enter username: ");
char[] pass = c.readPassword("Enter password: ");
// Data in and out
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
out.writeDouble(2.0);
out.writeInt(2);
out.writeUTF("123");
double price = in.readDouble();
int unit = in.readInt();
String desc = in.readUTF();
// Object in and out
ObjectInputStream in = new ObjectInputStream(new FileInputStream(dataFile));
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(dataFile));
Object ob0 = new Object();
out.writeObject(ob);
Object ob1 = in.readObject();
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import java.io.IOException
import java.io.BufferedReader;
import java.io.BufferedWriter;
Path file1 = Paths.get(src);
Path file2 = Paths.get(dest);
byte[] bytes = Files.readAllBytes(file1);
List<String> lines = Files.readAllLines(file1);
Files.write(file2, bytes);
Files.write(file2, lines);
reader = Files.newBufferedReader(file1, charset);
writer = Files.newBufferedWriter(file2, charset);
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line, 0, line.length());
writer.newLine();
}
Temp file:
Path tempFile = Files.createTempFile("/tmp", ".myapp");
List directory:
public void getDir(Path dir, LinkedList<Path> list)
{
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
if (Files.isDirectory(file))
{
getDir(file, list);
}
else
{
list.add(file);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
List directory for particular extensions:
public void getDir(Path dir, String extension, LinkedList<Path> list)
{
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
if (Files.isDirectory(file))
{
getDir(file, extension, list);
}
else
{
if (file.toString().endsWith(extension))
list.add(file);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
import java.net.Socket;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
public class EchoServer {
public static void main(String[] args) {
try {
// Create server socket
int port = Integer.parseInt(args[0]);
int limit = Integer.parseInt(args[1]);
int count = 0;
ServerSocket server = new ServerSocket(port);
// Create a thread pool for execution
ExecutorService pool = Executors.newFixedThreadPool(limit);
while (true) {
// accept a connection;
Socket client = server.accept();
count = count + 1;
// create a thread to deal with the client;
EchoHandler handler = new EchoHandler(client, count);
pool.submit(handler);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class EchoHandler implements Runnable {
private Socket client;
private int id;
EchoHandler(Socket client, int id) {
this.client = client;
this.id = id;
}
public void run()
{
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedOutputStream(client.getOutputStream()));
String line = null;
String msg = null;
do
{
line = in.readLine();
msg = String.format("%5d> %s", id, line);
out.println(msg);
out.flush();
} while ((line != null) && !line.equals("exit"));
in.close();
out.close();
client.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BatchProcessing {
public static void main(String[] args) {
try {
// Number of jobs and number of worker threads
int totalJobs = Integer.parseInt(args[0]);
int totalWorkers = Integer.parseInt(args[1]);
// Job queue
ConcurrentLinkedQueue<String> jobs = new ConcurrentLinkedQueue<String>();
// Fill the job queue with some jobs to work with
for (int i=0; i<totalJobs; i++)
{
String jobId = String.format("ID-%06d", i);
jobs.add(jobId);
}
/*
// Create the number of threads needed
Thread[] workers = new Thread[totalWorkers];
for (int i=0; i<totalWorkers; i++) {
workers[i] = new Thread(new WorkHandler(i, jobs));
workers[i].start();
}
// Wait for all threads to finish execution
for (int i=0; i<totalWorkers; i++)
{
workers[i].join();
}
*/
ExecutorService pool = Executors.newFixedThreadPool(totalWorkers);
for (int i=0; i<totalWorkers; i++) {
pool.submit(new WorkHandler(i, jobs));
}
pool.shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class WorkHandler implements Runnable {
private final int id;
private final ConcurrentLinkedQueue<String> jobs;
WorkHandler(int id, ConcurrentLinkedQueue<String> jobs) {
this.id = id;
this.jobs = jobs;
}
public void run() {
boolean doMoreWork = true;
while (doMoreWork)
{
try {
String jobId = jobs.poll();
if (jobId != null)
{
System.out.println(id + "\t" + jobId);
// Do some work here
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
else
{
doMoreWork = false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
System.out.println(id + "\tNo more work to do, exiting...");
}
}
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.ForkJoinPool;
public class ForkInvert extends RecursiveAction {
private int window = 8;
private int[] mSource;
private int[] mDestination;
private int mStart, mLength;
public ForkInvert(int[] src, int start, int length, int[] dst) {
mSource = src;
mStart = start;
mLength = length;
mDestination = dst;
}
protected void computeDirectly() {
for (int i=0; i<mLength; i++) {
mDestination[mStart+i] = 10000 - mSource[mStart+i];
}
}
protected void compute() {
if (mLength < window) {
computeDirectly();
return;
}
int split = mLength / 2;
invokeAll(new ForkInvert(mSource, mStart, split, mDestination),
new ForkInvert(mSource, mStart + split, mLength - split, mDestination));
}
public static void main(String[] args) throws Exception {
int[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int[] out = new int[in.length];
for (int i=0; i<in.length; i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
ForkInvert fi = new ForkInvert(in, 0, in.length, out);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(fi);
for (int i=0; i<out.length; i++)
{
System.out.print(out[i] + "\t");
}
System.out.println();
}
}
# Total CPU cores
int cores = Runtime.getRuntime().availableProcessors();
# High performance random number
int r = ThreadLocalRandom.current().nextInt(4, 77);
# Load properties
Properties props = new Properties();
FileInputStream in = new FileInputStream("conf.properties");
props.load(in);
in.close();
System.out.println(props.get("hostname"));
System.out.println(props.get("hostport"));
# Environment variables
Map<String, String> env = System.getenv();
System.out.println(env.get("PATH"));
# StringTokenizer
String input = "A:B:C:1234,abcd ABC CDE KDB";
StringTokenizer st = new StringTokenizer(input, ":, ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
# String split
String[] tokens = input.split("[:,\\s]+");
for (int i=0; i<tokens.length; i++)
{
System.out.println(tokens[i] + "\t" + tokens[i].length());
}
# Character Classes
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
# Quantifiers
Greedy Reluctant Possessive Meaning
X? X?? X?+ X, once or not at all
X* X*? X*+ X, zero or more times
X+ X+? X++ X, one or more times
X{n} X{n}? X{n}+ X, exactly n times
X{n,} X{n,}? X{n,}+ X, at least n times
X{n,m} X{n,m}? X{n,m}+ X, at least n but not more than m times
# Boundaries
^ The beginning of a line
$ The end of a line
\b A word boundary
\B A non-word boundary
\A The beginning of the input
\G The end of the previous match
\Z The end of the input but for the final terminator, if any
\z The end of the input
# Embedded Flags
Pattern.CANON_EQ None
Pattern.CASE_INSENSITIVE (?i)
Pattern.COMMENTS (?x)
Pattern.MULTILINE (?m)
Pattern.DOTALL (?s)
Pattern.LITERAL None
Pattern.UNICODE_CASE (?u)
Pattern.UNIX_LINES (?d)
RMI_HOST=`wget -q -O - http://169.254.169.254/latest/meta-data/public-ipv4`
RMI_PORT=7091
java \
-Djava.rmi.server.hostname=$RMI_HOST \
-Dcom.sun.management.jmxremote.port=$RMI_PORT \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.ssl=false \
MyApp
# Shuffle
Collections.shuffle(c);
# Deduplication
Set<E> set = c.stream()
.collect(Collectors.toSet()); // no duplicates
Collection<Type> noDups = new LinkedHashSet<Type>(c);
# Join
String joined = elements.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
Set<Type> union = new HashSet<Type>(s1);
union.addAll(s2);
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
Set<Type> difference = new HashSet<Type>(s1);
difference.removeAll(s2);
# Sum
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
# Run a single class, with space delimited arguments
mvn exec:java -Dexec.mainClass="net.qyjohn.samples.App" -Dexec.args="A B C"
# Run a single class, with comma delimited arguments
mvn exec:java -Dexec.mainClass="net.qyjohn.samples.App" -Dexec.arguments="A B,C"
# Run all tests
mvn test
# Run a single test class
mvn test -Dtest=TestClass
# Run a single test method
mvn test -Dtest=TestClass#testMethod
# Run multiple test method
mvn test -Dtest=TestClass#testMethod1+testMethod2
import java.util.logging.Logger;
private final static Logger LOGGER = Logger.getLogger(Compute.class.getName());
# severe, warning, info, config, fine, finer, finest
LOGGER.info("This is the log message.");
logging.properties
# Logging
handlers = java.util.logging.ConsoleHandler
.level = FINEST
java.util.logging.ConsoleHandler.level=FINEST
# My App
net.qyjohn.samples.level = CONFIG
net.qyjohn.samples.handler = java.util.logging.ConsoleHandler
Specify logging.properties
java -Djava.util.logging.config.file=./logging.properties net.qyjohn.samples.App [args]