Compilation
Compile
javac Hello.java
Compile to specific JRE version
javac -source 1.8 -target 1.8
Run compiled file
java Hello
Java code snippets
Hello World
public class Hello {
public static void main(String[] args) {
System.out.println(java.lang.System.getenv("PATH"));
}
}
Create file
import java.io.File;
public class Hello {
public static void main(String[] args) {
/* Create file */
File f=new File("/tmp/test.txt");
try {
f.createNewFile();
} catch(Exception e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
public class Hello {
public static void main(String[] args) throws IOException {
java.io.File f=new java.io.File("/tmp/test.txt");
f.createNewFile();
}
}
Read file (ReadFile.java
)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("/etc/passwd"))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Runtime exec
import java.util.*;
import java.io.*;
public class f
{
public static void main(String args[])
{
try
{
System.out.println(args[0]);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(args[0]);
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
Java keystore
generate new keystore
keytool -keystore clientkeystore -genkey -alias client
import certificate to keystore
keytool -import -alias alias -file ./cert.pem -keystore /etc/ssl/certs/java/cacerts
use custom keystore
java -Djavax.net.ssl.trustStore=/path/to/keystore
Add PEM certificate to Java keystore
Combine certificate and key into one file
cat certificate.pem privatekey.pem > combined.pem
Add to Java keystore:
keytool -import -trustcacerts -alias yourdomain -file combined.pem -keystore yourkeystore.jks
Other
Java change heap size to 2GB
java -Xmx2g