0% found this document useful (0 votes)
4 views40 pages

Unit 4 Java (Print File)

The document provides an overview of Java's Input-Output (IO) operations, detailing standard input and output streams such as System.in, System.out, and System.err. It explains the types of streams (Input and Output) and categorizes them into ByteStream and CharacterStream, along with examples of various classes like FileInputStream, FileOutputStream, FileReader, and FileWriter. Additionally, it covers the Reader and Writer classes, their constructors, and methods for reading and writing character streams.

Uploaded by

vanshajgoel01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views40 pages

Unit 4 Java (Print File)

The document provides an overview of Java's Input-Output (IO) operations, detailing standard input and output streams such as System.in, System.out, and System.err. It explains the types of streams (Input and Output) and categorizes them into ByteStream and CharacterStream, along with examples of various classes like FileInputStream, FileOutputStream, FileReader, and FileWriter. Additionally, it covers the Reader and Writer classes, their constructors, and methods for reading and writing character streams.

Uploaded by

vanshajgoel01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT 4

Java IO : Input-output in Java with Examples


 brings various Streams with its I/O package that helps the user to perform all the inpuoutput operations.
These streams







 Java support all the types of objects, data-types, characters, files etc. to fully execute the I/O operations

Before exploring various input and output streams let’s look at 3 standard or default streams that Java has
to provide which are also most common in use:

[Link]
This is the standard input stream([Link]) that is used to read characters from the keyboard or any
other standard input device.
[Link]
This is the standard output stream([Link]) that is used to produce the result of a program on an
output device like the computer screen. Here is a list of the various print functions that we use to output
statements:
– print(): This method in Java is used to display a text on the console. This text is passed as the parameter to
this method in the form of String. This method prints the text on the console and the cursor remains at the end
of the text at the console. The next printing takes place from just here.
Syntax:
[Link](parameter);
Example:
// Java code to illustrate print()
import [Link].*;

class Demo_print {
public static void main(String[] args)
{

// using print()
// all are printed in the
// same line
[Link]("GfG! ");
[Link]("GfG! ");
[Link]("GfG! ");
}
}

Output
GfG! GfG! GfG!
– println(): This method in Java is also used to display a text on the console. It prints the text on the console
and the cursor moves to the start of the next line at the console. The next printing takes place from the next
line.
Syntax:
[Link](parameter);
Example:
// Java code to illustrate println()
import [Link].*;

class Demo_print {
public static void main(String[] args)
{

// using println()
// all are printed in the
// different line
[Link]("GfG! ");
[Link]("GfG! ");
[Link]("GfG! ");
}
}

Output
GfG!
GfG!
GfG!
– printf(): This is the easiest of all methods as this is similar to printf in C. Note that [Link]() and
[Link]() take a single argument, but printf() may take multiple arguments. This is used to format
the output in Java.
Example:
// A Java program to demonstrate
// working of printf() in Java
class JavaFormatter1 {
public static void main(String[] args) {
int x = 100;

// Printing a simple integer


[Link]("Printing simple integer:
x = %d %n", x);

// Printing a floating-point
// number with precision
[Link]("Formatted with precision:
PI = %.2f%n", [Link]);

float n = 5.2f;

// Formatting a float to 4 decimal places


[Link]("Formatted to specific width:
n = %.4f%n", n);

n = 2324435.3f;

// Right-aligning and formatting a


// float to 20-character width
[Link]("Formatted to right margin:
n = %20.4f%n", n);
}
}

Output
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
[Link] Example
To demonstrate the usage of [Link] with print():
// Java Program demonstrating [Link]
public class Main {

public static void main(String[] args) {

// Using print()
[Link]("This is an error message
using print().\n");

// Using println()
[Link]("This is another error
message using println().");

// Using printf()
[Link]("Error code: %d, Message:
%s%n", 404, "Not Found");
}
}
Output:
This is an error message using print().
This is another error message using println().
Error code: 404, Message: Not Found
Types of Streams
Depending on the type of operations, streams can be divided into two primary classes:
Input Stream: These streams are used to read data that must be taken as an input from a source array or file
or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral
device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.

Depending on the types of file, Streams can be divided into two primary classes which can be further
divided into other classes as can be seen through the diagram below followed by the explanations.
ByteStream
This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the
FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:
Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method
Stream class Description

BufferedOutputStrea
This is used for Buffered Output Stream.
m

This contains method for writing java standard data


DataOutputStream
types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.

Example:
// Java Program illustrating the
// Byte Stream to copy
// contents of one file to another file.
import [Link].*;
public class BStream {
public static void main(
String[] args) throws IOException
{

FileInputStream sourceStream = null;


FileOutputStream targetStream = null;

try {
sourceStream
= new FileInputStream("[Link]");
targetStream
= new FileOutputStream("[Link]");

// Reading source file and writing


// content to target file byte by byte
int temp;
while ((
temp = [Link]())
!= -1)
[Link]((byte)temp);
}
finally {
if (sourceStream != null)
[Link]();
if (targetStream != null)
[Link]();
}
}
}

Output:
Shows contents of file [Link]
CharacterStream
In Java, characters are stored using Unicode conventions (Refer this for details). Character stream
automatically allows us to read/write data character by character. Though it has many classes, the FileReader
and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read
from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:
Stream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReade
This output stream is used to translate character to byte.
r
Stream class Description

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.

Java Reader Class



Reader class in Java is an abstract class used for reading character streams. It serves as the base class for
various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more
efficient implementations of the read() method. To work with the Reader class, we must extend it and
implement its methods. The read() is the key method for reading characters.
Example: The below Java Program demonstrates how to read a text file character by character using the
Reader class.
import [Link].*;

public class Geeks {

public static void main(String[] args)


{

// Try-catch block for exception handling


try {

// Create a FileReader object


// which is a subclass of Reader
Reader r = new FileReader("[Link]");

// Read one character at a time from the file


int data = [Link]();
while (data != -1) {

// Convert the int to char and print


[Link]((char)data);
data = [Link]();
}

// Close the reader


[Link]();
}
catch (Exception ex) {

// Handle any IO exceptions


[Link]("An error occurred: "
+ [Link]());
}
}
}

Output :

Declaration of Reader Class


Declaration of Reader class is given below:
public abstract class Reader implements Readable, Closeable

Key Points
1. abstract class
 The Reader class is an abstract class means it cannot be instantiated directly.
 It is designed to be extended by either classes like FileReader, BufferedReader.
2. Implements Readable
The Reader class implements Readable Interface
int read(CharBuffer cb) throws IOException;
3. Implements Closeable
The Reader class implements Closeable Interface
void close() throws IOException;

Constructors of Reader Class


There are two constructors used with Java Reader Class as mentioned below:
1. protected Reader()
Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
2. protected Reader(Object lock)
 Creates a new character-stream reader whose critical sections will synchronize on the given object.
 Parameter: The object used to synchronize the operations of the Reader.
Methods of Java Reader Class
1. abstract void close()
Closes the stream and releases any system resources associated with it. Once the stream has been closed,
further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously
closed stream has no effect.
Syntax:
public abstract void close() throws IOException
Throws: IOException
2. void mark(int readAheadLimit)
Marks the present position in the [Link] calls to reset() will attempt to reposition the stream to
this point. Not all character-input streams support the mark() operation.
Syntax:
public void mark(int readAheadLimit) throws IOException
 Parameter: readAheadLimit – Limit on the number of characters that may be read while still preserving
the mark. After reading this many characters, attempting to reset the stream may fail.
 Throws: IOException
3. boolean markSupported()
Tells whether this stream supports the mark() operation. The default implementation always returns false.
Subclasses should override this method.
Syntax:
public boolean markSupported()
Return Type:
 Return True if the input stream supports mark() and reset() methods.
 Return False is the input stream does not support these methods.
4. int read()
Reads a single character. This method will block until a character is available, an I/O error occurs, or the end
of the stream is reached. Subclasses that intend to support efficient single-character input should override
this method.
Syntax:
public int read() throws IOException
Return Type:
 Return the next byte of data as an integer in the range 0 to 255.
 Return -1 if the end of the stream is reached
Throws: IOException
5. int read(char[] cbuf)
Reads characters into an array. This method will block until some input is available, an I/O error occurs, or
the end of the stream is reached.
Syntax:
public int read(char[] cbuf) throws IOException
Parmeter:
 char[] cbuf: A character array provided by the caller where the characters read from the stream will be
stored.
Return Type:
 Return the number of character actually read.
 Return -1 if the end of the stream is reached.
Throws: IOException
6. abstract int read(char[] cbuf, int off, int len)
Reads characters into a portion of an array. This method will block until some input is available, an I/O error
occurs, or the end of the stream is reached.
Syntax:
public abstract int read(char[] cbuf,int off,int len) throws IOException
Parameter:
 char[] cbuf: The character array where the characters will be stored.
 int off: The starting index in the array where the first character will be stored.
 int len: Maximum number of characters to read
Return Type:
 Return the number of character actually read and stored in the buffer.
 Return -1 if the end of the stream is reached.
Throws: IOException
7. int read(CharBuffer target)
Attempts to read characters into the specified character buffer. The buffer is used as a repository of
characters as-is: the only changes made are the results of a put operation. No flipping or rewinding of the
buffer is performed.
Synatx:
public int read(CharBuffer target) throws IOException
Parameter:
 CharBuffer target: A CharBuffer into which characters are read.
Return type:
 The number of characters read into the buffer.
 Return -1 if the end of the stream is reached.
Throws:
 IOException
 NullPointerException
 ReadOnlyBufferException
8. boolean ready()
Tells whether this stream is ready to be read.
Synatx:
public boolean ready() throws IOException

Return Type:
 Return True if the stream is ready to read.
 Return False if the stream is not ready.
Throws: IOException
9. void reset()
Resets the stream. If the stream has been marked, then attempt to reposition it at the mark. If the stream
has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example
by repositioning it to its starting point. Not all character-input streams support the reset() operation, and
some support reset() without supporting mark().
Synatx:
public void reset() throws IOException
Throws: IOException
10. long skip(long n)
Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of
the stream is reached.
Syntax:
public long skip(long n) throws IOException
Parameter: long n: The number of bytes or characters to skip in the stream. If n is negative, the method
does nothing
Return Type: Return the number of character actually skipped.
Throws:
 IOException
 IllegalArgumentException(if n is negative)

Java Writer Class



Java writer class is an abstract class in the [Link] package. It is designed for writing character streams.
Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an
abstract class, we cannot create an instance of it directly. Instead, we will use one of its concrete subclasses
such as FileWriter, BufferedWriter, or PrintWriter.
Example 1: The below Java program demonstrates the working of the FileWriter class to write data to
a text file.
// Demonstrate the woking of FileWriter class
import [Link];
import [Link];

public class Geeks {


public static void main(String[] args)
{
try {

// Create a FileWriter to write to a file named


// "[Link]"
FileWriter w = new FileWriter("[Link]");

// Write a simple message to the file


[Link]("Hello, World!");

// Close the writer


[Link]();

[Link](
"Geeks for Geeks");
}
catch (IOException e) {
[Link]("An error occurred: "
+ [Link]());
}
}
}
Output
Geeks for Geeks

Declaration of the Writer Class


public abstract class Writer extends Object implements Appendable, Closeable, Flushable

Constructors of the Writer Class


The Writer class in Java has two protected constructors that allow for the creation of character streams with
synchronization capabilities.
1. Protected Writer(): Creates a new character stream that can itself synchronize on the writer.
2. protected Writer(Object obj): Creates a new character stream that can itself synchronize on the given
object – ‘obj’.
Java Writer Class Methods
There are certain methods associated with the Java Writer class as mentioned below:
1. write(int char)
 Itwrites a single character to the character stream.
 Characters being written are contained in 16 lower bits of the ‘char’ integer value, the rest of the 16 higher
bits are ignored by the method.
Syntax:
public void write(int char)
 Parameter: Theinteger value of the character to be written.
 Return type: This method does not return any value
 Exception: Throws IOException if an I/O error occurs during writing.
2. write(String str)
It writes a string to the character stream.
Syntax:
public void write(String str)
 Parameter: string to be written to the character stream.
 Return type: This method does not return any value
 Exception: Throws IOException if an I/O error occurs during writing.
3. write(String str, int offset, int maxlen)
It writes some part of the string to the character stream.
Syntax:
public void write(String str, int offset, int maxlen)
 Parameter:
o str: string to be written to the character stream.
o offset: start position of the String
o maxlen: maximum length upto which string has to written
 Return type: This method does not return any value
 Exception: Throws IndexOutOfBoundsException if the offset or maxlen is invalid, and IOException if an I/O
error occurs.
4. write(char[] carray)
It writes character array to the character stream.
Syntax:
public void write(char[] carray)
 Parameter: Thecharacter array to be written to the character stream
 Return type: This method does not return any value
 Exception: Throws IOException if an I/O error occurs during writing.
5. write(char[] carray, int offset, int maxlen)
It writes some part of the character array to the character stream.
Syntax:
public abstract void write(char[] carray, int offset, int maxlen)
 Parameter:
o carray: character to be written to the character stream
o offset: start position of the character array
o maxlen: maximum no. of the character of the carray has to written
 Return type: This method does not return any value
 Exception: Throws IndexOutOfBoundsException if the offset or maxlen is invalid, and IOException if an I/O
error occurs.
6. close()
It closes the character stream, flushing it first.
Syntax:
public abstract void close()
 Parameter: This method does not take any parameter.
 Return type: This method does not return any value.
 Exception: Throws IOException if an I/O error occurs during closing.
7. flush()
It flushes the Writer stream. Flushing one stream invocation will flush all other buffer in chain.
Syntax:
public void flush()
 Parameter: This method does not take any parameter.
 Return type: This method does not return any value.
 Exception: Throws IOException if an I/O error occurs while flushing.
8. append(char Sw)
It appends a single character to the Writer.
Syntax:
public Writer append(char Sw)
 Parameter: character to be append
 Return type: This method return a writer.
 Exception: Throws IOException if an I/O error occurs during appending.
9. append(CharSequence char_sq)
It appends specified character sequence to the Writer.
Syntax:
public Writer append(CharSequence char_sq)
 Parameter: Character sequence to append.
 Return type: This method return a writer, if char sequence is null, then NULL appends to the Writer.
 Exception: Throws NullPointerException if the char_sq is null and IOException if an I/O error occurs during
appending.
10. append(CharSequence char_sq, int start, int end)
It appends specified part of a character sequence to the Writer.
Syntax:
public Writer append(CharSequence char_sq, int start, int end)
 Parameter:
o char_sq: Character sequence to append.
o start: start of character in the Char Sequence
o end: end of character in the Char Sequence
 Return type: This method does not return value.
 Exception: Throws IndexOutOfBoundsException if the start or end values are invalid, and IOException if an
I/O error occurs.

Explain how we can do Database connectivity with MS-Access in Java with Notepad explain with
example.
To establish database connectivity with MS Access in Java using Notepad (or any simple text editor) for writing the code, you can follow these steps:

Prerequisites:

1. MS Access Database: You should have an MS Access database file (either .accdb or .mdb format).
2. JDBC Driver: For Java to communicate with MS Access, you'll need a JDBC driver. One popular choice is the UCanAccess JDBC driver.
3. Java JDK: Make sure you have the Java Development Kit (JDK) installed.
4. Notepad: You will write the Java code in Notepad or any other simple text editor.

Steps to Connect to MS Access in Java Using Notepad:

Step 1: Download UCanAccess JDBC Driver

1. Go to the UCanAccess GitHub page or Maven repository to download the required JAR files.
2. Download the latest [Link] and other required dependencies such as:
o [Link]
o [Link]
o [Link]

For simplicity, download all the JAR files and save them in a folder, such as C:/ucanaccess/.
Step 2: Write Java Code in Notepad

1. Open Notepad (or any simple text editor).


2. Write the Java code to establish a connection to MS Access using the UCanAccess JDBC driver.

Here's an example of how you can write the code:

Explanation of Code:

1. JDBC URL: The URL to access your MS Access database is specified as:

java
Copy
String dbURL = "jdbc:ucanaccess://C:/path/to/your/[Link]";

Replace "C:/path/to/your/[Link]" with the actual path to your MS Access file.

2. Driver Class: The [Link]("[Link]") loads the UCanAccess JDBC driver. This allows Java to use the
UCanAccess JDBC URL.
3. SQL Query: Replace YourTable with the actual name of your table in the MS Access database.
4. ResultSet: The ResultSet is used to retrieve data returned by the query. The code extracts values from the database and prints them to the console.
5. Exception Handling: The code uses try-catch blocks to handle potential SQLException and ClassNotFoundException exceptions.
6. Resource Management: It's important to close the Connection, Statement, and ResultSet objects to free up resources.

Step 3: Save the Java File

1. In Notepad, go to File > Save As.


2. Name your file [Link].
3. Choose All Files from the file type dropdown and save it to a folder (e.g., C:/Projects/AccessDBConnection/).

Step 4: Compile the Java Code

1. Open Command Prompt (Windows) or Terminal (Mac/Linux).


2. Navigate to the directory where your [Link] file is saved. For example:

bash
Copy
cd C:/Projects/AccessDBConnection/

3. Set the classpath to include the UCanAccess JAR files you downloaded. For example, if your JAR files are located in C:/ucanaccess/, you can set the classpath
as follows:

bash
Copy
set CLASSPATH=C:/ucanaccess/[Link];C:/ucanaccess/[Link];C:/ucanaccess/commons-logging-
[Link];.

4. Compile the Java file using javac:

bash
Copy
javac [Link]

Step 5: Run the Java Code

1. After compiling, run the Java program using the java command:

bash
Copy
java AccessDBConnection

If everything is set up correctly, the program will connect to the MS Access database and display the results in the console.

Step 6: Troubleshooting

 If you encounter errors like ClassNotFoundException, make sure the JDBC driver JARs are included in your classpath.
 If there are issues with the connection, double-check the path to your .accdb file and ensure it is correct.
 If the MS Access file is password-protected, you can pass the password in the getConnection method.

Conclusion:

By following these steps, you can use Notepad (or any simple text editor) to write a Java program that connects to an MS Access database. You will use UCanAccess as
the JDBC driver to perform database operations. Make sure you have the required JAR files in your classpath when compiling and running the Java code.
Explain how we can do Database connectivity with Oracle in Java with Notepad explain with
example.
To establish a connection with an Oracle database in Java using Notepad (or any simple text editor) for writing the code, follow these steps. This example
uses JDBC (Java Database Connectivity) and assumes you have an Oracle database instance already set up.

Prerequisites:

1. Oracle Database: Ensure you have access to an Oracle database, with a username, password, and a table to work with.
2. JDBC Driver: Oracle provides the Oracle JDBC driver (usually in the form of a .jar file), which you will need to download.
3. Java JDK: Make sure you have the Java Development Kit (JDK) installed on your machine.
4. Notepad: Use Notepad or any text editor to write the Java code.

Steps to Connect to Oracle Database in Java Using Notepad:

Step 1: Download Oracle JDBC Driver

1. Download the Oracle JDBC driver (e.g., [Link]) from the Oracle website or use Maven if you're working in a Maven project.
2. Place the [Link] file in a folder on your system, for example, C:/oracle_jdbc/.

Step 2: Write Java Code in Notepad

1. Open Notepad (or any simple text editor).


2. Write the Java code to establish a connection to Oracle using the Oracle JDBC driver.

Here’s an example Java program that demonstrates how to connect to an Oracle database:

Explanation of the Code:

1. JDBC URL: The connection URL for Oracle databases typically follows this format:

java
Copy
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
o localhost: The Oracle database server (you may need to replace this with the IP address or hostname of your Oracle database).
o 1521: The default port for Oracle Database.
o orcl: The Oracle SID (System Identifier). Replace this with your actual database SID if different.
2. Driver Class: We use the [Link] to load the Oracle JDBC driver. In modern Java setups, this might not be necessary because
the JDBC driver can be automatically discovered, but it is still included for compatibility.
3. SQL Query: In the code above, the SQL query retrieves all data from the your_table table. Replace your_table with an actual table name from
your Oracle database.
4. ResultSet: The ResultSet is used to store the results of the query. The while loop iterates through the rows, retrieving data from the columns (ID,
NAME in this case) and printing them.
5. Exception Handling: We handle ClassNotFoundException (if the JDBC driver is not found) and SQLException (if there are issues with the
database connection or query).
6. Resource Management: It's important to close the Connection, Statement, and ResultSet objects to avoid memory leaks. This is done in the
finally block.

Step 3: Save the Java File

1. In Notepad, go to File > Save As.


2. Name the file [Link].
3. Save it to a folder, e.g., C:/Projects/OracleDBConnection/.

Step 4: Compile the Java Code

1. Open Command Prompt (Windows) or Terminal (Mac/Linux).


2. Navigate to the directory where you saved the Java file:

bash
Copy
cd C:/Projects/OracleDBConnection/

3. Set the classpath to include the [Link] file:

bash
Copy
set CLASSPATH=C:/oracle_jdbc/[Link];.

Make sure to replace C:/oracle_jdbc/[Link] with the actual path to your JDBC driver JAR file.
4. Compile the Java file using javac:

bash
Copy
javac [Link]

Step 5: Run the Java Code

1. After compiling, run the program using the java command:

bash
Copy
java OracleDBConnection

If everything is set up correctly, the program will connect to the Oracle database, execute the SQL query, and display the results in the console.

Step 6: Troubleshooting

 If you get a ClassNotFoundException, it means the JDBC driver is not found. Ensure that the [Link] is included in your classpath.
 If the connection fails, verify the following:
o The database URL (SID, host, and port).
o The username and password are correct.
o The Oracle database is running and accessible.

Conclusion:

By following these steps, you can easily connect to an Oracle database from a Java application using Notepad (or any simple text editor). You need to
include the appropriate Oracle JDBC driver ([Link]) in your classpath, write the Java code to establish a connection, and execute SQL queries to
interact with the database.

Explain how we can do Database connectivity with MYSQL server in Java with Notepad explain with
example.
To establish a connection with a MySQL database in Java using Notepad (or any text editor), follow these steps. This example uses JDBC (Java Database Connectivity)
and assumes you have a MySQL server running.
Prerequisites:

1. MySQL Server: You should have MySQL installed and running on your machine (or use a remote MySQL server).
2. JDBC Driver for MySQL: You need the MySQL JDBC driver (also known as Connector/J), which enables Java to interact with MySQL databases.
3. Java JDK: Make sure you have Java Development Kit (JDK) installed on your machine.
4. Notepad: Use Notepad or any text editor to write the Java code.

Steps to Connect to MySQL Database in Java Using Notepad:

Step 1: Download MySQL JDBC Driver

1. Download the MySQL JDBC driver (Connector/J) from the MySQL official site.
2. The driver will be in the form of a .jar file (e.g., [Link]).
3. Save the .jar file in a folder, for example: C:/mysql_jdbc/.

Step 2: Write Java Code in Notepad

1. Open Notepad (or any simple text editor).


2. Write the Java code to establish a connection to the MySQL database using the JDBC driver.

Here’s an example Java program:

Explanation of the Code:

1. JDBC URL: The JDBC URL format for MySQL is:

java
Copy
String url = "jdbc:mysql://localhost:3306/your_database";

o localhost: The host where the MySQL server is running (use an IP address or domain name for a remote server).
o 3306: The default port for MySQL.
o your_database: The name of the database you want to connect to. Replace it with your actual database name.
2. Driver Class: We load the MySQL JDBC driver using:

java
Copy
[Link]("[Link]");

This is optional in newer versions of Java but is included for compatibility.

3. SQL Query: Replace your_table with the actual table you want to query. The code retrieves data from this table.
4. ResultSet: We process the ResultSet returned by the executeQuery() method, extracting values from the columns (ID and Name in this case).
5. Exception Handling: The code uses try-catch blocks to handle any ClassNotFoundException or SQLException.
6. Resource Management: The finally block ensures that the Connection, Statement, and ResultSet are closed properly to avoid resource leaks.

Step 3: Save the Java File

1. In Notepad, go to File > Save As.


2. Name the file [Link].
3. Save it to a folder, for example, C:/Projects/MySQLDBConnection/.

Step 4: Compile the Java Code

1. Open Command Prompt (Windows) or Terminal (Mac/Linux).


2. Navigate to the directory where you saved the Java file:

bash
Copy
cd C:/Projects/MySQLDBConnection/

3. Set the classpath to include the [Link] file:

bash
Copy
set CLASSPATH=C:/mysql_jdbc/[Link];.

Replace C:/mysql_jdbc/[Link] with the actual path to the .jar file.

4. Compile the Java file using javac:

bash
Copy
javac [Link]
Step 5: Run the Java Code

1. After compiling, run the program using the java command:

bash
Copy
java MySQLDBConnection

If everything is set up correctly, the program will connect to the MySQL database, execute the query, and display the results in the console.

Step 6: Troubleshooting

 ClassNotFoundException: If you get a ClassNotFoundException, it means that the MySQL JDBC driver is not found. Ensure that the .jar file is included in
your classpath.
 SQLException: If the connection fails, check the following:
o Ensure MySQL is running and accessible.
o Verify the database URL, username, and password.
o Ensure the table name is correct and exists in the database.

Conclusion:

By following these steps, you can easily establish a JDBC connection to MySQL using Notepad (or any simple text editor). You'll need to include the MySQL JDBC driver
in your classpath, write the Java code to connect to the MySQL server, and execute SQL queries.

Object Serialization in Java


Serialization is the process of converting an object's state (i.e., its fields and data) into a byte stream, which can be persisted (e.g., saved to a file) or
transmitted over a network. Deserialization is the reverse process, where the byte stream is converted back into a Java object.

In Java, serialization is used to save an object's state to a persistent storage or transfer it between different layers or systems (e.g., between a client and
server). It is essential for situations like writing objects to files, sending objects over a network, or saving data between sessions.

Key Concepts of Object Serialization


1. Serializable Interface:
To enable an object to be serialized, the class of that object must implement the [Link] interface. This is a marker interface,
meaning it does not contain any methods. It serves to indicate that the class can be serialized.

Why Serialization is Important

1. Persistence: Serialization allows Java objects to be saved to files, databases, or other storage mediums, allowing them to be retrieved and used later.
2. Networking: Serialization enables the transfer of Java objects over a network, such as sending data between a client and server.
3. Session Management: Serialized objects can be stored and reloaded between application sessions (e.g., storing user sessions in a web application).

Limitations of Serialization

1. Non-Serializable Fields: If an object contains a field that is not serializable (i.e., the field's class does not implement Serializable), serialization
will fail unless the field is marked as transient.
2. Versioning Issues: When a class evolves (e.g., fields are added or removed), deserialization can fail if the serialVersionUID is not properly
managed, leading to potential incompatibility issues.
3. Security Concerns: Deserialization of objects can introduce security risks if data from untrusted sources is deserialized. Malicious code could
potentially execute during deserialization, so it’s important to validate and sanitize input.

Socket Programming in Java




Socket programming in Java allows different programs to communicate with each other over a network,
whether they are running on the same machine or different ones. This article describes a very basic one-way
Client and Server setup, where a Client connects, sends messages to the server and the server shows them
using a socket connection. There is a lot of low-level stuff that needs to happen for these things to work but
the Java API networking package ([Link]) takes care of all of that, making network programming very easy
for programmers.
Note: A “socket” is an endpoint for sending and receiving data across a network.
Client-Side Programming
1. Establish a Socket Connection
To connect to another machine we need a socket connection. A socket connection means both machines
know each other’s IP address and TCP port. The [Link] class is used to create a socket.
Socket socket = new Socket(“[Link]”, 5000)
 The first argument: The IP address of Server i.e. [Link] is the IP address of localhost, where code
will run on the single stand-alone machine.
 The second argument: The TCP Port number (Just a number representing which application to run on a
server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
2. Communication
To exchange data over a socket connection, streams are used for input and output:
 Input Stream: Reads data coming from the socket.
 Output Stream: Sends data through the socket.
Example to access these streams:
// to read data
InputStream input = [Link]();
// to send data
OutputStream output = [Link]();
3. Closing the Connection
The socket connection is closed explicitly once the message to the server is sent.
Example: Here, in the below program the Client keeps reading input from a user and sends it to the server
until “Over” is typed.

Server-Side Programming
1. Establish a Socket Connection
To create a server application two sockets are needed.
 ServerSocket: This socket waits for incoming client requests. It listens for connections on a specific port.
 Socket: Once a connection is established, the server uses this socket to communicate with the client.
2. Communication
 Once the connection is established, you can send and receive data through the socket using streams.
 The getOutputStream() method is used to send data to the client.
3. Close the Connection
Once communication is finished, it’s important to close the socket and the input/output streams to free up
resources.
Example: The below Java program demonstrate the server-side programming

Explanation: In the above example, we have implemented a server that listens on a specific port, accepts a
client connection, and reads messages sent by the client. The server displays the messages until “Over” is
received, after which it closes the connection and terminates.
Important Points:
 Server application makes a ServerSocket on a specific port which is 5000. This starts our Server listening
for client requests coming in for port 5000.
 Then Server makes a new Socket to communicate with the client.
socket = [Link]()
 The accept() method blocks(just sits there) until a client connects to the server.
 Then we take input from the socket using getInputStream() method. Our Server keeps receiving messages
until the Client sends “Over”.
 After we’re done we close the connection by closing the socket and the input stream.
 To run the Client and Server application on your machine, compile both of them. Then first run the server
application and then run the Client application.
Run the Application
Open two windows one for Server and another for Client.
1. Run the Server
First run the Server application as:
$ java Server
Output:
Server started
Waiting for a client …
2. Run the Client
Then run the Client application on another terminal as
$ java Client
Output:
Connected
3. Exchange Messages
 Type messages in the Client window.
 Messages will appear in the Server window.
 Type “Over” to close the connection.
Here is a sample interaction,
Client:
Hello
I made my first socket connection
Over
Server:
Hello
I made my first socket connection
Over
Closing connection
Notice that sending “Over” closes the connection between the Client and the Server just like said before.
Note : If you’re using Eclipse or likes of such:
1. Compile both of them on two different terminals or tabs
2. Run the Server program first
3. Then run the Client program
4. Type messages in the Client Window which will be received and shown by the Server Window
simultaneously.
5. Type Over to end.

Client-Server Architecture - System Design





Client-server architecture is a fundamental concept in system design where a network involves multiple clients
and a server. Clients are devices or programs that request services or resources, while the server is a powerful
machine providing these resources or services. This architecture allows efficient data management and
resource sharing, making it popular in web applications, databases, and other network-based systems. By
separating roles and distributing tasks, client-server architecture enhances performance, scalability, and
security.

Client-Server Architecture

What is Client-Server Architecture?


Client-server architecture is a cornerstone of modern system design, where the network infrastructure is
structured to include multiple clients and a central server. In this model, clients are devices or programs that
make requests for services or resources, while the server is a powerful machine or software that fulfills these
requests. Communication between clients and the server follows a request-response protocol, such as
HTTP/HTTPS for web services or SQL for database queries.
 This architecture allows for efficient data management and resource allocation by centralizing critical
functions on the server, which can handle complex processing and large-scale data storage.
 Clients manage user interactions and send specific requests to the server, which processes these requests
and sends back appropriate responses.
 The client-server architecture is highly scalable, as it can accommodate more clients by scaling the server's
capabilities or adding additional servers.
 This design is prevalent in various applications, including web services, database management, and email
systems, providing a robust framework for developing and managing complex, distributed systems
efficiently.
Importance in System Design
Client-server architecture is critically important in system design for several reasons:
 Centralized Management: By centralizing resources and services on a server, this architecture simplifies
maintenance, updates, and security management. Administrators can efficiently monitor and manage data,
apply updates, and enforce security policies from a single location.
 Scalability: Client-server architecture supports scalability. As the number of clients grows, additional
servers can be added, or existing server capacities can be expanded to handle increased demand without
significantly altering the overall system architecture.
 Resource Optimization: This model allows for optimized resource allocation. Servers are designed to
handle intensive processing and large data storage, while clients are optimized for user interactions and
requests. This separation ensures efficient use of system resources.
 Reliability and Availability: With robust server infrastructure, client-server systems can ensure high
reliability and availability. Redundancies, backups, and load balancing techniques can be implemented on
the server side to minimize downtime and ensure continuous service availability.
 Enhanced Security: Centralized servers enable better security controls and data protection measures.
Sensitive data can be securely stored on servers, and access can be tightly controlled and monitored.
Encryption and authentication mechanisms can be more effectively implemented.
Key Components of Client Server Architecture
Client-server architecture in system design involves several key components that work together to ensure
efficient communication, resource management, and service delivery. Here are the main components:
 Client: The client is a device or application that requests services or resources from the server. It initiates
communication with the server and processes the results returned by the server.
 Server: The server is a powerful machine or application that provides services or resources to clients. It
processes client requests, performs the necessary computations or data retrieval, and sends back the
appropriate responses.
 Network: The network facilitates communication between clients and servers. It enables data exchange
using various protocols and ensures reliable connectivity.
 Protocols: Protocols are standardized rules that govern data transmission and communication between
clients and servers. They ensure that data is transmitted in a secure, reliable, and understood manner.
 Middleware: Middleware is software that acts as an intermediary between clients and servers. It provides
additional functionalities like authentication, logging, message queuing, and transaction management.
 Database: A database is a structured collection of data stored on the server. It stores and manages data
that clients request, ensuring data consistency, integrity, and security.
 User Interface (UI): The UI is the part of the client application that interacts with the user. It provides a
means for users to input data and view results returned by the server.
 Application Logic: Application logic refers to the code and algorithms that define the application's
functionality. It processes user inputs, interacts with the server, and manages the flow of data between the
client and the server.
 Server Responds with Data: The server responds to the API requests with the required data. This data is
sent back to the client-side application.
 Data Fills Placeholders: The data fetched from the APIs fills the placeholders in the client interface. The
page becomes fully interactive and visible to the user.

Development of Client-Server Applications in Java

A client-server application is a software architecture where the client (requesting party) communicates with the server (providing service) over a network. The client
sends requests to the server, and the server processes those requests and sends back the appropriate responses.

In Java, a client-server application is typically developed using sockets and Java networking APIs. The client communicates with the server via network protocols, usually
over TCP/IP or UDP, using the Java Socket API.

Key Concepts of Client-Server Architecture

1. Client:
o A program that sends requests to a server and waits for the server’s response.
o Typically, the client is a user-facing application (e.g., a web browser, a desktop application) that interacts with the server.
2. Server:
o A program that listens for incoming client requests, processes them, and sends back responses.
o The server is usually a long-running program that waits for client connections.
3. Socket:
o A socket is an endpoint for communication between two machines over a network.
o In Java, the [Link] class is used by clients, and the [Link] class is used by servers to listen for incoming connections.

Steps to Develop a Basic Client-Server Application in Java

We'll break down the client-server application development process into two parts: server and client.

1. Server Side Development

The server is responsible for waiting for client connections, accepting those connections, processing the client's request, and sending a response back.

Steps to Create a Server:

1. Create a ServerSocket to listen for client connections.


2. Accept the client connection using accept().
3. Create Input/Output Streams to send and receive data from the client.
4. Process the request and send a response.
5. Close the connection after processing the request.

Example of a Simple Server Code in Java:

Explanation:

1. ServerSocket is created on port 12345 and listens for client connections.


2. accept() waits for an incoming connection from a client and establishes a connection when one is made.
3. BufferedReader is used to read data from the client, and PrintWriter is used to send data to the client.
4. The server reads a message from the client and sends a response.
5. After the interaction, the connection is closed using close().

2. Client Side Development

The client is responsible for connecting to the server, sending a request, and receiving the server’s response.

Steps to Create a Client:

1. Create a Socket and connect to the server using the server’s IP address and port number.
2. Create Input/Output Streams to send and receive data to/from the server.
3. Send a request to the server.
4. Receive the response from the server.
5. Close the connection.

Example of a Simple Client Code in Java:

Explanation:

1. Socket is created with the server's IP (localhost) and port (12345).


2. PrintWriter sends data to the server, and BufferedReader receives the server's response.
3. The client sends a message to the server ("Hello Server!") and reads the response ("Hello from the server!").
4. The connection is closed after the communication is completed.

Running the Application

1. Run the Server: Start the Server program first. The server will listen for incoming connections.
2. Run the Client: Start the Client program next. The client will connect to the server, send a request, and print the server's response.

Client-Server Communication Process:

1. The client creates a socket and connects to the server on the specified port.
2. The server accepts the connection and creates a new socket for communication.
3. The client sends a request (message).
4. The server processes the request and sends a response.
5. The client receives the response and prints it.
6. Both the client and server close their sockets after communication.

Enhancements and Considerations:

 Multi-threading: In real-world scenarios, the server often uses threads to handle multiple client connections concurrently. This can be done using Thread or
ExecutorService.
 Exception Handling: It's important to handle exceptions and manage resources properly to avoid resource leaks (e.g., closing sockets and streams).
 Security: For secure communication, you can implement SSL/TLS encryption using SSLSocket and SSLServerSocket.
 Data Formats: In complex applications, it’s common to use data formats like JSON, XML, or Protocol Buffers for sending structured data between the client and
server.

Example of Multi-threaded Server:

Design of a Multithreaded Server in Java

A multithreaded server in Java is designed to handle multiple client connections concurrently. It allows a server to serve multiple clients simultaneously,
without having to wait for one client's request to be completely processed before accepting another. Each client request is handled by a separate thread,
enabling better performance, scalability, and responsiveness.

Key Concepts

1. Threading in Java:
o Java allows the creation of multiple threads using the Thread class or implementing the Runnable interface.
o A multithreaded server creates a new thread for each client request, ensuring that the server can handle multiple clients simultaneously.
2. ServerSocket:
o The ServerSocket class is used by the server to listen for incoming client connections.
o The server creates a ServerSocket bound to a specific port (e.g., 12345). It listens for client connections on that port and accepts them one by
one.
3. Client-Server Communication:
o Once a client connects to the server, the server needs to handle that request. Instead of blocking the main thread while it processes the request,
the server spawns a new thread dedicated to the client's communication.
4. Thread Pool (Optional):
o For efficiency, a thread pool (using ExecutorService) can be used to manage threads, ensuring that resources are reused rather than creating
a new thread for every client connection. This improves scalability and prevents resource exhaustion when the number of clients is large.

Steps to Design a Multithreaded Server in Java

1. Create a ServerSocket to listen for client connections.


2. Accept client connections in a loop.
3. For each connection, create a new thread to handle the client’s request.
4. Use Input/Output streams to communicate with the client.
5. Close resources after the client has been served.

Example of a Simple Multithreaded Server in Java


In this example, we'll create a simple server that listens on port 12345 and spawns a new thread for each client connection.

Explanation of the Code:

1. ServerSocket:
o The server creates a ServerSocket on port 12345, which listens for incoming client connections.
o The server keeps running and listening for client connections using [Link](). When a client connects, the server accepts the
connection and returns a Socket object for communication.
2. ClientHandler (Thread):
o Each client connection is handled by a separate thread. The ClientHandler class extends Thread and handles the interaction between the
server and the client.
o Inside the run() method, the server reads messages from the client using an InputStreamReader wrapped in a BufferedReader. It then
sends a response back to the client using a PrintWriter.
3. Thread Creation:
o For each client connection, the server creates a new instance of the ClientHandler thread and starts it using new
ClientHandler(clientSocket).start(). This allows multiple clients to be served concurrently.
4. I/O Communication:
o The server reads data sent by the client and sends a response. It uses BufferedReader for reading the client’s message and PrintWriter for
writing a response to the client.
5. Close Resources:
o After the client request is processed, the BufferedReader, PrintWriter, and Socket are closed to free up resources.

2. Improvements and Considerations:

1. Thread Pooling:
o Instead of creating a new thread for each client, which could exhaust resources when there are many clients, we can use a thread pool to
efficiently manage a pool of threads. Java provides ExecutorService for this purpose.
o Example using ExecutorService for thread pooling:
o In this version, [Link](10) creates a thread pool with a maximum of 10 threads. When a client connects, the
server submits the ClientHandler task to the pool. The pool manages the threads and reuses them, improving efficiency.
2. Graceful Shutdown:
o The server should be able to shut down gracefully, releasing resources like sockets and threads. You can handle this by adding proper
exception handling, handling interrupts, and ensuring that resources are closed when the server is stopped.
3. Handling Client Timeouts and Errors:
o It's important to handle timeouts and potential errors when communicating with clients. For example, if a client is not responsive, the server
should handle the timeout and close the connection properly.
o You can set socket timeouts using [Link](int timeout).
4. Security:
o For secure communication, you should consider using SSL/TLS encryption to protect data transmitted between the client and server.
o You can use Java’s SSLSocket and SSLServerSocket classes for secure communication.
5. Concurrency Control:
o In some applications, you may need to synchronize access to shared resources (e.g., a shared database or file). This can be done by using
synchronization mechanisms like synchronized blocks, ReentrantLocks, or other concurrency utilities provided in the
[Link] package.

Advantages of Multithreaded Server Design:

1. Concurrency:
o Each client is served by a separate thread, allowing the server to handle multiple client requests simultaneously, which is especially important
in high-traffic scenarios.
2. Responsiveness:
o The server can interact with multiple clients concurrently, ensuring that one client does not block others while it waits for a response.
3. Scalability:
o The server can scale better by managing resources (e.g., threads) more efficiently, especially when using a thread pool.
4. Maintainability:
o The use of threads allows the server code to be cleaner and easier to maintain since each thread can be focused on handling a single client’s
request.

Conclusion:

Designing a multithreaded server in Java involves using a ServerSocket to accept client connections and creating a new thread (or using a thread pool) for
each client request. Threads allow concurrent processing of multiple client requests, which improves the server’s scalability and responsiveness. With
appropriate thread management, such as using thread pools, and considering factors like security and error handling, you can build efficient and reliable
multithreaded servers in Java.

You might also like