Java - auto-mate/CheatSheetWiki GitHub Wiki
- Basics
Below is an example of using basic variables printing and reading command line, reading SQL and file reading and writing.
Put .java files in same directory.
Run info in file appWrapperClass.java.
Main Entry point is "public static void main(String[] args)"
File appWrapperClass.java:
// imports
// java.util.Scanner to read from command line
import java.util.Scanner;
// compile with javac
// or in vsc with java export jar
// run with java -jar appWrapperClass.jar
// class to hold main
class appWrapperClass {
public static void main(String[] args) {
// Print to Command Line
System.out.println("Hello World");
// Create Scanner to Read from command line
Scanner nS = new Scanner(System.in);
// Read from command line
String readFromConsol = nS.nextLine();
// Create string
String reply = "reply: ";
// Print Concatenated Vars
System.out.println(reply + readFromConsol);
nS.close(); // only use if console input not required again!
// Create String Array
String[] sA = new String[2];
// Add Values to Array
sA[0] = "A";
sA[1] = "B";
// Loop and print Array Values
for (int i = 0; i < sA.length; i++) {
System.out.println(sA[i]);
}
// Basic if statement
if (sA[1] == "B") {
System.out.println("Yep its B");
} else {
System.out.println("Nope not B");
}
// Create integer variable
int x = 10;
// Basic while loop
while (x > 0) {
System.out.println(x);
x -= 1;
}
// try catch - demo divide by zero error
try {
int z = 1 / 0;
} catch (Exception e) {
// TODO: handle exception
System.out.println("Oh Dear: " + e);
}
// Call static function in same class
newFunc();
// Call static function in extended from this class (external file in same directory)
names.wotcher();
// Call static function in non extended class with var (external file in same directory)
other.stuff("some");
// Call static function in non extended class (external file in same directory)
fileHandling.makeFile();
fileHandling.readFile();
}
// 2nd static function in this class
static void newFunc() {
// Print to Command Line
System.out.println("From newFunc.");
}
}
File fileHandling.java:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class fileHandling {
public static void makeFile() {
// Make New File
File x = new File("FromJava.txt");
try {
FileWriter fw = new FileWriter(x.getName());
// Write To New File
fw.append("Hello");
// Close Writer
fw.close();
// open Writer For Existing File
fw = new FileWriter("toapp.txt", true);
// make BufferedWriter for multi append efficiency
BufferedWriter bw = new BufferedWriter(fw);
// make PrintWriter to Write from BufferedWriter for multi append efficiency
PrintWriter pw = new PrintWriter(bw);
// Append Line
pw.println("Hello App\n");
// Close PrintWriter
pw.close();
// Close BufferWriter
bw.close();
// Close FileWriter
fw.close();
} catch (Exception e) {
// handle exception
System.out.println("OOPS - Error In makefile function");
// quit app
System.exit(0);
}
}
public static void readFile() {
try {
// make FileReader
FileReader fr = new FileReader("toapp.txt");
// get 1 st char as int
int z = fr.read();
// if int = -1 then EOF
// Loop all read values
while (z > 0) {
// print int returned as its character
System.out.print(Character.toChars(z));
// read next character
z = fr.read();
}
// Close the FileReader
fr.close();
} catch (Exception e) {
// handle exception
System.out.println("OOPS - Error Reading File");
// quit app
System.exit(0);
}
}
}
File names.java:
public class names extends appWrapperClass {
static void wotcher() {
// Print Line
System.out.println("wotcher");
}
}
File other.java: import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet;
public class other {
// function requiring a string parameter
public static void stuff(String prefix) {
// Print Line of variable concatanated with string
System.out.println(prefix + " other stuff");
// Run a Function
sqeel();
}
// SQL Read And Print
// Need to add Referenced Library mssql-jdbc-12.6.1.jre8.jar (based on runtime etc)
// Add directly in VSC with VSC recommended java extensions
// Available as zip download from MS
// - see also .vscode/settings.json
public static void sqeel() {
// Try Catch
try {
// Make a Connection Object
Connection conn = DriverManager.getConnection(
"jdbc:sqlserver://<SERVER_NAME>;Database=<DATABASE_NAME>;user=<USER>;password=<PASSWORD>;trustServerCertificate=true");
// Print Connection Confirmation
System.out.println("Yay sqeel connected!");
// Make SQL statement Object
Statement stmt = conn.createStatement();
// Make SQL ResultSet Object and populate with data from SQL Query (stmt.executeQuery(<SQL>))
ResultSet rs = stmt
.executeQuery("SELECT TOP 10 [<FIELD1>],[<FIELD2>] FROM <TABLE_OR_VIEW>");
// Loop using .next() on ResultSet
while (rs.next()) {
System.out.println(
// Print Field Values with rs.getString(<SQL_FIELD_NAME>)
rs.getString("<FIELD1>") + ":" +
rs.getString("<FIELD2>"));
}
// Close ResultSet
rs.close();
// Close Statement
stmt.close();
// Close Connection
conn.close();
} catch (Exception e) {
// handle exception: write "Boo:" + error details
System.out.println("Boo: " + e);
// Exit App
System.exit(0);
}
}
}