Java Fundamentals: JDBC, File I/O, and Network Socket Programming

Java Database Connectivity (JDBC) Implementation

This example demonstrates establishing a connection to a MySQL database, executing a complex SQL query, and processing the resulting data set. Note the use of standard Java naming conventions and proper exception handling.

JDBC Connection and Data Retrieval Code (Cs391Jdbc1.java)


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;

public class Cs391Jdbc1 {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            // 1. Load the JDBC Driver (Legacy method)
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            
            // 2. Database Credentials and URL
            String dbUser = "cs391";
            String dbPass = "abc123";
            String dbUrl = "jdbc:mysql://localhost/test";
            
            // 3. Establish Connection
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
            System.out.println("Connection established successfully.");
            
            // 4. Create Statement and Execute Query
            Statement s = conn.createStatement();
            
            // SQL query fixed to use standard syntax and 'AND' operator
            String sqlQuery = "SELECT * FROM students, classes, studentinclass " +
                              "WHERE students.sid = studentinclass.sid AND classes.cid = studentinclass.cid;";
            
            s.executeQuery(sqlQuery);
            ResultSet rs = s.getResultSet();
            
            int count = 0;
            
            // 5. Process Results
            while (rs.next()) {
                String name = rs.getString("name");
                String prof = rs.getString("prof");
                // Assuming 'coolnessfactor' is the intended column name
                int coolnessFactor = rs.getInt("coolnessfactor"); 
                System.out.println(name + '\t' + prof + "\t" + coolnessFactor);
                count++;
            }
            
            // 6. Close Resources
            rs.close();
            s.close();
            System.out.println("Found " + count + " rows.");               
        } catch (Exception e) {
            // Improved error message
            System.out.println("An error occurred with the database connection:\n" + e.toString());
        } finally {
            // 7. Ensure Connection Closure
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("Connection closed.");
                } catch (SQLException e) {
                    // Ignore closing errors
                }
            }
        }
    }
}

Handling File Input and Output (I/O)

This program demonstrates how to use the Scanner class for reading user input and file content, and the PrintStream class for writing output to a file. It includes robust error checking for file existence and readability, and calculates the average of integers found in the input file.

File I/O Implementation (Cs391FileIo.java)


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

public class Cs391FileIo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a filename: ");
        String filename = in.nextLine();
        
        File f = new File(filename);
        
        // Input validation loop: Ensure file exists and is readable
        while (!f.canRead()) {
            System.out.println("Bad filename! File cannot be read or does not exist.");
            System.out.println("Enter a filename: ");
            filename = in.nextLine();
            f = new File(filename);
        }
        
        int count = 0;
        int sum = 0;
        Scanner infile = null;
        
        try {
            infile = new Scanner(f);
            
            // Read integers from the file, calculate sum and count
            while (infile.hasNextInt()) {
                sum += infile.nextInt();
                count++;
            }
            
        } catch (FileNotFoundException ex) {
            System.out.println("Error: File not found during Scanner initialization.");
        } finally {
            if (infile != null) {
                infile.close();
            }
        }
        
        PrintStream out = null;
        
        try {
            // Open file for writing output
            out = new PrintStream("average.txt");
            
            if (count > 0) {
                out.println("Average is: " + ((double) sum / count));
            } else {
                out.println("No numbers found in the input file.");
            }
            
        } catch (FileNotFoundException ex) {
            System.out.println("Error: Could not create output file average.txt");
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

Basic TCP Socket Client: Making an HTTP Request

This code demonstrates fundamental TCP socket programming by connecting to a web server (www.poly.edu on port 80) and issuing a basic HTTP 1.0 GET request. It uses Scanner and PrintStream for stream handling over the socket.

Socket Client Implementation (CS391Socket1.java)


package cs391socket1; 

import java.net.Socket;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;

public class CS391Socket1 {
    public static void main(String[] args) {
        Socket s = null;
        Scanner sin = null;
        PrintStream sout = null;
        
        try {
            // Connect to the server (www.poly.edu on port 80)
            s = new Socket("www.poly.edu", 80);
            sin = new Scanner(s.getInputStream());
            sout = new PrintStream(s.getOutputStream());
            
            // Send HTTP GET request
            sout.print("GET / HTTP/1.0\r\nhost: www.poly.edu\r\n\r\n");
            
            // Read and print response lines
            String line;
            while (sin.hasNext()) {
                line = sin.nextLine();
                System.out.println(line);
            }
            
        } catch (IOException ex) {
            System.out.println("Connection Failed: " + ex.getMessage());
        } finally {
            // Ensure socket closure
            try {
                if (s != null) {
                    s.close();
                }
            } catch (IOException ex) {
                // Handle closure exception if necessary
            }
        }
    }
}

Multithreaded TCP Socket Server Implementation

This example sets up a simple server listening on port 5190. It uses a continuous loop to accept incoming client connections and delegates the handling of each client to a separate thread (HandleClient class), allowing concurrent communication. The server logs client IP addresses and messages until the client sends the “QUIT” command.

Server Main Class (CS391Server1.java)


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class CS391Server1 {
    public static void main(String[] args) throws IOException {
        // Server listens on port 5190
        ServerSocket ss = new ServerSocket(5190);
        System.out.println("Server started, listening on port 5190...");
        
        while (true) {
            // Wait for a client connection
            Socket client = ss.accept();
            // Start a new thread to handle the client
            new HandleClient(client).start();
        }
    }
}

Client Handler Thread (HandleClient.java)


import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

class HandleClient extends Thread {
    private Socket client;
    
    HandleClient(Socket news) {
        this.client = news;
    }
    
    @Override
    public void run() {
        PrintStream out = null;
        String ip = client.getInetAddress().getHostAddress();
        
        try {
            System.out.println("Connection established from: " + ip);
            out = new PrintStream(client.getOutputStream());
            Scanner in = new Scanner(client.getInputStream());
            
            // Read the first line
            String line = in.nextLine();
            
            // Loop until the client sends "QUIT"
            while (!line.equals("QUIT")) {
                System.out.println(ip + ": " + line);
                try {
                    // Attempt to read the next line
                    line = in.nextLine();
                } catch (Exception e) {
                    // Connection closed abruptly
                    break; 
                }
            }
            
        } catch (IOException ex) {
            System.err.println("I/O error handling client " + ip + ": " + ex.getMessage());
        } finally {
            // Ensure client socket closure
            try {
                client.close();
                System.out.println("Connection lost from: " + ip);
            } catch (IOException ex) {
                // Ignore closure errors
            }
        }
    }
}