Java File Handling: How to read and write to a file with MySQL and how to handle BLOB data?

What will you learn?

  1. Write a program to read data from a file and write it to another file.
  2. Write a program to read blob data (audio or video) with MySQL.

Write a program to read data from a file and write it to another file.

For this program, the input and output will be the following:

Input: text in one file (.txt or .docx or other)

Output: same text in another file

In this problem, our task is to read the data that are in one file (say, input.txt), and write the same data in another file (say, output.txt).

We have several methods to perform this task. I am using FileInputStream and FileOutputStream which are the example of Byte stream classes because they read the data in binary format. FileInputStream class obtains input bytes from a file whereas FileOutputStream class is used for writing data to a file.
The java.io package provides these classes. This java.io package contains nearly every class that we need to perform input and output operations in Java programming language.

package file;

import java.io.*;

public class Read_Write {

    public static void main(String[] args) {
    FileInputStream input = null;
    FileOutputStream output = null;
		
    try {
	File inFile = new File("E:\\inputFile.docx");
	File outFile = new File("E:\\outputFile.docx");
			
	input = new FileInputStream(inFile);
	output = new FileOutputStream(outFile);
			
	//The buffer size for reading data
	byte[] buffer = new byte[1024];
			
	while(input.read(buffer)>0) {
	    output.write(buffer);
	}
			
	input.close();
	output.close();
			
	System.out.println("Successfully writen to another file....");	
    }catch(IOException e) {
	System.out.println("IO exception occur");
    }	
    }
}

Note: This is the example of Byte Stream Classes (FileInputStream and FileOutputStream)

Another we have: Character Stream Classes (FileReader and FileWriter)

Blob data type - Read/Write audio/video with Mysql | Java programming language

This is a tutorial on Blob data types to read/write audio/video files with Mysql. A blob is a binary large object that can hold a huge amount of data with a maximum length of 65535 characters.

In this tutorial, I have explained how can you store blob data type in a database. This includes the following steps:

  • First of all, connect Java to the database using the getConnection() method.
  • Then create a statement.
  • Write SQL query.
  • The final step is to execute the statement.

ReadBlobFile.java:

package Ishwar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class ReadBlobFile {

    public static void main(String[] args) throws Exception  {

	// connection
	Connection conn = DbConnect.getConnection();
		
	//sql query
	Statement stmt = conn.createStatement();
	String sql = "select resume from blob_table where id=4";
	ResultSet rs = stmt.executeQuery(sql);
	
	// Read audio from blob data type
	File file = new File("E://java/myaudio.mp3");
	FileOutputStream output = new FileOutputStream(file);
	
	if(rs.next()) {
            InputStream input = rs.getBinaryStream("resume");
			
	    byte[] buffer = new byte[1024];
	    while(input.read(buffer)>0) {
		output.write(buffer);
	    }
	}	
	System.out.println("Audio is successfully readable....");	

WriteBlobFile.java:

package Ishwar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class WriteBlobFile {

    public static void main(String[] args) throws SQLException  {
	// BLOB --> Binary Large Object
		
	//connection
	Connection conn=null;
		
	//Sql query
	String sql = "update blob_table set resume=? where id=4";
	PreparedStatement stmt = null;
	try {
	    stmt = conn.prepareStatement(sql);
	} catch (SQLException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
		
	//Insert audio in blob data type
	File file = new File("E://java/audio1.mp3");
	FileInputStream input;
	try {
	    input = new FileInputStream(file);
	    stmt.setBinaryStream(1, input);
	    stmt.executeUpdate();
	    System.out.println("Audio is succesfully inserted...");
	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    System.out.println("File is not located in specified location...."

DbConnect.java:

This connection part is very important in every topic related to Java database connectivity. It is very good practice to write this connection part separately and use it in any program where it is required.

package Ishwar;

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

public class DbConnect {
    static String databaseURL = "jdbc:mysql://localhost:3306/java";
    static String user="root";
    static String password = "";
	
    public static Connection getConnection() {
	Connection conn=null;
	try {
	    Class.forName("com.mysql.jdbc.Driver");
	    try {
		conn = DriverManager.getConnection(databaseURL,user,password);
	    } catch (SQLException e) {
		System.out.println(e);
	    }
	} catch (ClassNotFoundException e) {
	    System.out.println("Class not found exception");
	}
	return conn;	
    }
}

Conclusion:

To sum up, this method offers a strong way to work with different types of files (File handling) like text, audio, and video using Java. This method lets us easily read and write various file formats.

I hope this post is very helpful to you. If you have any questions, you can ask me in the comment section. I will reply as soon as possible. Thanks.