









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
An overview of java's capabilities in handling file i/o operations and database connectivity using jdbc. It covers byte streams and character streams for file manipulation, including reading and writing files, and managing file system operations such as creating, deleting, and renaming files. Additionally, it explains how to connect to relational databases using jdbc, execute sql queries, and process results, with examples of inserting, updating, and deleting data. The document also discusses the types of jdbc drivers and their roles in database communication. Useful for understanding basic file management and database interaction in java, providing practical examples and explanations of key concepts. It is designed to help developers implement file operations and database connections in their java applications, covering essential topics such as stream handling, file management, and jdbc driver types. (447 characters)
Typology: Study notes
1 / 17
This page cannot be seen from the preview
Don't miss anything!
A File Stream in Java is a way to read from or write to a file.
Just like water flows through a pipe , data flows through a stream in Java. You can use this stream to:
Read data from a file (input) Write data to a file (output)
1.Byte stream:
A Byte Stream in Java is a mechanism that allows reading and writing of raw binary data in the form
of 8-bit bytes. It is part of the java.io package and is used to perform I/O operations on binary files like images, audio, and other non-text files. Byte streams are built upon the InputStream and
OutputStream abstract classes and offer precise control over file data, especially where character encoding is not required or relevant.
There are two main abstract classes that form the core of byte stream architecture in Java:
InputStream: This is the superclass for all classes that represent an input stream of bytes. It defines methods for reading bytes from a source. OutputStream: This is the superclass for all classes that represent an output stream of bytes. It defines methods for writing bytes to a destination.
Some commonly used subclasses of these are:
FileInputStream: Used to read bytes from a file. FileOutputStream: Used to write bytes to a file.
Reading with FileInputStream
import java.io.*;
public class ByteReadExample { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("input.txt");
int byteData; while ((byteData = fis.read()) != -1) { System.out.print((char) byteData); }
fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
What it does:
Opens input.txt. Reads each byte until the end of file (-1). Converts each byte to a character and prints it.
Writing with FileOutputStream
import java.io.*;
public class ByteWriteExample { public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream("output.txt");
String message = "Hello using byte stream!"; byte[] data = message.getBytes(); // convert string to bytes
fos.write(data); fos.close();
System.out.println("Data written successfully."); } catch (IOException e) { e.printStackTrace(); } } }
What it does:
Converts a string into a byte array. Writes that byte data into output.txt.
2. character streams
Character Streams are used in Java to handle text data. These streams work with 16-bit Unicode characters , making them ideal for handling textual data in various character encoding formats (like UTF-8, UTF-16).
Java's character streams provide an easy way to read and write text data while automatically handling character encoding and decoding. These streams are more efficient
Writing to a Text File Using FileWriter
The FileWriter class is used to write text data to a file in the form of characters.
Example (Writing Text File with FileWriter ) import java.io.*;
public class CharacterWriteExample { public static void main(String[] args) { try { // Creating a FileWriter object to write to the file "output.txt" FileWriter fw = new FileWriter("output.txt");
String message = "Hello, this is a text file written with FileWriter!"; // Writing the message to the file fw.write(message);
// Closing the FileWriter after use fw.close();
System.out.println("Data written successfully."); } catch (IOException e) { e.printStackTrace(); // Handling any IOExceptions (e.g., write failure) } } }
In Java, the File class (found in the java.io package) is used to represent files and directories.
It provides a variety of methods for creating, deleting, and managing files and directories, as
well as retrieving file metadata like size, name, and permissions.
Unlike Streams (which are used for reading and writing file content), the File class is mainly
for performing file system operations such as checking if a file exists, creating new files, renaming files, and getting file properties.
Common Methods of the File Class
1. File Creation Methods
createNewFile() : Creates a new empty file on the disk. Returns true if the file was created, false if the file already exists. mkdir() : Creates a new directory. mkdirs() : Creates the directory and all necessary parent directories.
2. File Information Methods
exists() : Checks if the file or directory exists. getName() : Returns the name of the file or directory. getAbsolutePath() : Returns the absolute path of the file. length() : Returns the length of the file in bytes (not applicable to directories). lastModified() : Returns the last modified time in milliseconds. isFile() : Checks if the object is a regular file. isDirectory() : Checks if the object is a directory. canRead(), canWrite(), canExecute() : Checks if the file has read, write, or execute permissions.
3. File Deletion Methods
delete() : Deletes the file or directory. If the file is not empty (in case of directories), it won't be deleted.
4. File Renaming and Moving Methods
renameTo(File dest) : Renames the file or moves it to a different location.
5. Listing Methods
list() : Returns an array of strings representing the names of files and directories in the current directory. listFiles() : Returns an array of File objects representing the files and directories in the current directory.
import java.io.*;
public class FileInfoExample { public static void main(String[] args) { File file = new File("example.txt");
if (file.exists()) { System.out.println("File Name: " + file.getName()); System.out.println("Absolute Path: " + file.getAbsolutePath()); System.out.println("Length: " + file.length() + " bytes"); System.out.println("Last Modified: " + file.lastModified()); System.out.println("Is it a file? " + file.isFile()); System.out.println("Is it a directory? " + file.isDirectory()); } else { System.out.println("File does not exist."); } } }
4. Creating a Directory
You can create a directory using the mkdir() or mkdirs() method.
import java.io.*;
public class CreateDirectoryExample { public static void main(String[] args) { File dir = new File("newDirectory");
// Create the directory if (dir.mkdir()) { System.out.println("Directory created: " + dir.getName()); } else { System.out.println("Directory already exists or failed to create."); } } }
5. Listing Files in a Directory
You can list all files and directories inside a directory using list() or listFiles() methods.
import java.io.*;
public class ListFilesExample { public static void main(String[] args) { File dir = new File("someDirectory");
if (dir.exists() && dir.isDirectory()) { // Listing file names inside the directory String[] files = dir.list(); for (String file : files) { System.out.println(file); } } else { System.out.println("Directory does not exist."); } } }
6. Renaming or Moving a File
You can use renameTo() to rename or move a file.
import java.io.*;
public class RenameFileExample { public static void main(String[] args) { File oldFile = new File("example.txt"); File newFile = new File("renamedExample.txt");
if (oldFile.renameTo(newFile)) { System.out.println("File renamed to: " + newFile.getName()); } else { System.out.println("File rename failed."); } } }
7. Deleting a File or Directory
The delete() method can be used to delete a file or directory. Be cautious: a directory must be empty to delete it.
import java.io.*;
public class DeleteFileExample { public static void main(String[] args) { File file = new File("example.txt");
if (file.delete()) { System.out.println("Deleted the file: " + file.getName()); } else { System.out.println("Failed to delete the file."); } } }
Steps for Connecting to a Database Using JDBC
Here’s an example that shows how to connect to a MySQL database and execute a simple SELECT query.
1. Add MySQL JDBC Driver
Before writing the code, make sure you have the JDBC driver for MySQL (e.g., mysql-
connector-java-x.x.x.jar) in your classpath. If you're using Maven, you can add the following
dependency to your pom.xml:
2. JDBC Code Example
import java.sql.*;
public class JDBCExample { public static void main(String[] args) { // Database URL, username, and password String url = "jdbc:mysql://localhost:3306/yourDatabase"; // Database URL
String user = "yourUsername"; // Database username String password = "yourPassword"; // Database password
// Step 1: Load the JDBC driver (this step is optional in JDBC 4.0 and above) try { Class.forName("com.mysql.cj.jdbc.Driver"); // Load MySQL JDBC driver
// Step 2: Establish a connection Connection conn = DriverManager.getConnection(url, user, password); System.out.println("Connected to the database.");
// Step 3: Create a statement Statement stmt = conn.createStatement();
// Step 4: Execute a query (e.g., SELECT) String query = "SELECT * FROM users"; // Example query ResultSet rs = stmt.executeQuery(query);
// Step 5: Process the result set while (rs.next()) { // Assume the "users" table has "id" and "name" columns int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); }
// Step 6: Close the result set, statement, and connection rs.close(); stmt.close(); conn.close();
} catch (ClassNotFoundException e) { System.out.println("JDBC Driver not found."); e.printStackTrace(); } catch (SQLException e) { System.out.println("Error while connecting to the database."); e.printStackTrace(); } } }
In the code, the SQLException is caught in case any SQL error occurs during the connection or
execution of queries. Similarly, ClassNotFoundException is caught if the JDBC driver is not found in the classpath.
// Executing a SELECT query String query = "SELECT id, name, age FROM users"; ResultSet rs = stmt.executeQuery(query);
// Processing the ResultSet while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age); }
// Closing resources rs.close(); stmt.close(); conn.close();
} catch (SQLException e) { e.printStackTrace(); } } }
Updating Data (Executing INSERT, UPDATE, DELETE Queries)
For updating the data in a database (i.e., inserting new records, updating existing records, or
deleting records), we use the executeUpdate() method of the Statement or PreparedStatement
interface. This method is used for any SQL statement that modifies the database (INSERT,
UPDATE, DELETE) but does not return any result set.
Steps for Updating Data :
Example: Inserting Data import java.sql.*;
public class InsertDataExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/yourDatabase"; String user = "yourUsername"; String password = "yourPassword";
try {
// Establishing a connection Connection conn = DriverManager.getConnection(url, user, password); System.out.println("Connected to the database.");
// Creating a statement Statement stmt = conn.createStatement();
// Executing an INSERT query String insertQuery = "INSERT INTO users (name, age) VALUES ('John Doe', 30)"; int rowsAffected = stmt.executeUpdate(insertQuery);
System.out.println("Inserted " + rowsAffected + " row(s).");
// Closing resources stmt.close(); conn.close();
} catch (SQLException e) { e.printStackTrace(); } } }
Example: Updating Data import java.sql.*;
public class UpdateDataExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/yourDatabase"; String user = "yourUsername"; String password = "yourPassword";
try { // Establishing a connection Connection conn = DriverManager.getConnection(url, user, password); System.out.println("Connected to the database.");
// Creating a statement Statement stmt = conn.createStatement();
// Executing an UPDATE query String updateQuery = "UPDATE users SET age = 31 WHERE name = 'John Doe'"; int rowsAffected = stmt.executeUpdate(updateQuery);
System.out.println("Updated " + rowsAffected + " row(s).");
// Closing resources stmt.close(); conn.close();
JDBC Drivers
A JDBC Driver is a set of classes and interfaces that allows Java applications to interact with
a specific database. JDBC drivers are required to translate Java calls into database-specific calls and to handle the details of database communication. There are several types of JDBC
drivers, each designed for different database communication methods. The right JDBC driver
depends on the type of database and how you intend to connect to it.
Types of JDBC Drivers
There are four types of JDBC drivers, each with its own strengths and use cases. These types
are categorized based on how they communicate with the database and the level of abstraction provided by the driver.
1. JDBC Type 1: JDBC-ODBC Bridge Driver
Description : This type of driver translates JDBC calls into ODBC calls. The JDBC- ODBC Bridge driver uses ODBC (Open Database Connectivity) to connect to the database, meaning that it relies on ODBC drivers to communicate with the database. How it Works : The Java application makes a JDBC call, which is translated into an ODBC call by the JDBC-ODBC Bridge. ODBC then communicates with the database. Advantages : o Works with any database that has an ODBC driver. Disadvantages : o The ODBC-Bridge is a separate layer, which can introduce performance overhead. o Deprecated : As of Java 8, the JDBC-ODBC Bridge is removed from the JDK, so this type of driver is rarely used today. Example : sun.jdbc.odbc.JdbcOdbcDriver (deprecated in newer versions of Java).
2. JDBC Type 2: Native API Driver
Description : This driver converts JDBC calls into database-specific calls by using the native API of the database. This means it requires a database-specific client installed on the system (such as a native library or DLL) to communicate with the database. How it Works : The Java application makes JDBC calls, which are translated into database-specific calls by the driver. These calls are executed using the database's own native API. Advantages : o Faster than Type 1 because it doesn't require the ODBC layer. Disadvantages : o Requires the installation of database-specific libraries on the client machine (database-specific). o Tied to a specific database, so it’s not portable across different database types. Example : Oracle's oracle.jdbc.driver.OracleDriver.
3. JDBC Type 3: Network Protocol Driver
Description : This driver uses a network protocol to communicate between the client application and the database. It is not dependent on any specific database and can connect to any database that supports the driver. How it Works : The Java application makes JDBC calls, which are translated into a database-independent protocol by the driver. This protocol is then sent to a middleware server that communicates with the actual database. Advantages : o Database-independent (can be used with different databases). o No need for a database-specific client on the local machine. Disadvantages : o There is an additional layer of middleware, which can introduce some overhead. o The middleware can be a potential point of failure. Example : IBM's DB2 JDBC driver (e.g., com.ibm.db2.jcc.DB2Driver).
4. JDBC Type 4: Thin Driver (Pure Java Driver)
Description : This is the most commonly used JDBC driver. The Type 4 driver is a pure Java driver that communicates directly with the database using the database's native protocol. This means it does not require any additional native code or client- side installation. How it Works : The Java application makes JDBC calls, which are directly translated into database-specific protocol calls. This is done entirely in Java without the need for any native code. Advantages : o No need for database-specific client installation or middleware. o Platform-independent and portable. o Fast and efficient since it directly communicates with the database using its native protocol. Disadvantages : o Tied to the database protocol. If the database changes its protocol, the driver may need to be updated. Example : MySQL's MySQL Connector/J (e.g., com.mysql.cj.jdbc.Driver) or PostgreSQL's JDBC driver (e.g., org.postgresql.Driver).