How To Store File Into Database Using Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

How to store file into database using Java?

Here I discussed on “How to store file into database using Java?“. As


we know that we can store image into database. Similarly we can store
file or large volume data into database. To store large volume of data or
text files into table, we can use CLOB data type. CLOB(Character
Large Object) used to store an entire file, large text data etc. into
column of table.

Suppose I create a table with table name InsertFile into Oracle


database.
create table InsertFile(FileData clob, FileNo int);
I used 2 columns. Column 1 for file storage and column 2 for file number.

Insert row into InsertFile table.


insert into InsertFile(FileNo) values(5);
It insert value 5 to FileNo column.

Follow steps to store file into table


1. First need to load text file into File object
File TxtFile=new File(“sample.txt”);

2. Attach file object to FileReader to read data from file.


FileReader fr=new FileReader(TxtFile);

3. Read data from FileReader and send it to First column of the


table using setCharacterStream() method.
pstmt.setCharacterStream(1,fr,(int)TxtFile.length());

It has 3 parameters
1 – It represents that data set to First column.
fr – Data read from fr.
(int)TxtFile.length() – length of the file.

4. Execute the statement using executeUpdate().


pstmt.executeUpdate();
Java example to store file into oracle database
1
2
3
// Java Example to store file into Oracle database
4 import java.sql.*;
5 import java.io.*;
6 public class FileInsertExample
7 {
public static void main(String[] args)
8 {
9 try
10 {
11 Class.forName("oracle.jdbc.driver.OracleDriver");
12 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
//Use PreparedStatement to update table. Here table is InsertFile.
13 PreparedStatement pstmt=con.prepareStatement("update InsertFile set F
14 //Load file into file object
15 File TxtFile=new File("sample.txt");
16 //Connect the file to FileReader for reading
FileReader fr=new FileReader(TxtFile);
17 //Write the file contents into the table
18 pstmt.setCharacterStream(1,fr,(int)TxtFile.length());
19 //Execute the statement
20 int i=pstmt.executeUpdate();
21
22 System.out.println("No. of records updated = "+i);
con.close();
23 }
24 catch (Exception e)
25 {
26 e.printStackTrace();
27 }
}
28 }
29
30
31

Output
Java file Name: FileInsertExample.java
D:\jdk1.7.0_02\bin> javac FileInsertExample.java
D:\jdk1.7.0_02\bin> java FileInsertExample
No. of records updated = 1

How to store images into database?


Hello friends, here I try to explain how to store images into database. I
discussed steps to insert images into database. It explains with a sample
example. In example, I store an image into Oracle database using Java
programming.
If we want to store images into database then we use BLOB data type to
store images. BLOB(Binary Large Object) is a SQL data type that
represents binary data to be stored into a database. BLOBs used to
store images, audio files or multimedia files.

Steps to store an image into database table


1. Create table with Blob data type. Here I used ImageData column to
store Image.

create table ImageTable(ImageData blob, ImageNo int);

2. First load image into File object.

File ImageFile= new File(“sampleImage.jpg”);

3. Attach the file object to FileInputStream for reading the image.

FileInputStream fis= new FileInputStream(ImageFile);

4. Read the image using FileInputStream and store it into the table using
setBinaryStream() method of Statement interface.
pstmt.setBinaryStream(1,fis,(int)ImageFile.length());
It has 3 parameters.
1 represents First column of ImageTable where the image should be
stored.
fis is a object of FileInputStream that read image.
ImageFile.length() gives ImageFile size in bytes.

pstmt is a object for PreparedStatement we use.

5. Execute the statement using executeUpdate().

pstmt.executeUpdate();

Thus we store image into database.

Java Example to store an image into database


1 // Java Example to store image into Oracle database
import java.sql.*;
2
import java.io.*;
3 public class ImageInsert
4 {
5 public static void main(String[] args)
6 {
7
8
9 try
10 {
11 Class.forName("oracle.jdbc.driver.OracleDriver");
12 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
//Use PreparedStatement to update table. Here table is ImageTable.
13 PreparedStatement pstmt=con.prepareStatement("update ImageTable set I
14 //Load image into file object
15 File ImageFile= new File("sampleImage.jpg");
16 //Attach the file object to FileInputStream for reading the image.
17 FileInputStream fis= new FileInputStream(ImageFile);
//Write the file contents into the table
18 pstmt.setBinaryStream(1,fis,(int)ImageFile.length());
19 //Execute the statement
20 int i=pstmt.executeUpdate();
21
22 System.out.println("No. of records updated = "+i);
23 con.close();
}
24 catch (Exception e)
25 {
26 e.printStackTrace();
27 }
}
28
}
29
30
31

Output
Java File Name: ImageInsert.java
D:\jdk1.7.0_02\bin> javac ImageInsert.java
D:\jdk1.7.0_02\bin> java ImageInsert
No. of records updated = 1

JVM – Is it Program or Machine?


Java Virtual Machine(JVM) is not a machine. It is a program. It is a free
program which is available on internet. JVM gives run time
environment to execute Java program. When we compile java file then
we get java bytecode(class file). It is not understandable by machine. So
bytecode can not directly execute on machine. So need of JVM. JVM
understands the bytecode and convert bytecode to machine level code.
So JVM is used to execute the bytecode.
Java virtual machine is a program which used in execution. It interacts
with operating system. So it is a platform specific. On internet different
version of JVM available for different operating system and processors.
If we write java code in Windows platform and we want to execute that
java code on Linux platform then we need Linux compatible JVM.

How JVM handles bytecodes?


JVM is the important part of entire java program execution. It is used to
convert each bytecode instruction into machine level code. Later that
machine code executed by microprocessor.
When Java bytecode(class) comes to JVM. First class loader subsystem
helps to allocate necessary memory to the java program. It verifies that
bytecodes are poper or not. If bytecode contains suspicious code then
JVM rejected it. JVM plays important role in security. Proper bytecodes
allocates necessary memory for execution the program. JVM execution
engine contains interpreter and JIT(Just In Time) compiler.Interpreter
and JIT compiler both work to convert bytecodes into machine code. JIT
compiler is a part of JVM which increase the speed of execution of java
bytecodes.

Conclusion
JVM is a program which used to execute java class files. JVM is a
platform dependent. For different operating systems different JVM
program available on internet. It is free available on internet. It converts
bytecodes instruction into the machine language instruction.

Why Java is the best suited language for internet?


Java is the best suitable language for internet compare than other
programming languages like C/C++. It is the best opted programming
language for networks.

The main reason is Java is a platform independent programming


language. When we compiled java code then we get java bytecode.
Java bytecode is a purely platform independent. You can run that
bytecode to any platform like Windows, Linux, Unix etc.
On internet different computers with different operating systems. Java
programs will run on any operating system and produce the same
results. So if we want to create any software then Java is a preferred
languages because it can be executed on any computer system without
any problem. So it is the best suited for internet and networks.

Example: I create a sample java program and stores it with


“sample.java“. Java program stores with .java extension. When we
compile it we will get .class extension file. Here we will get
“sample.class” file. Class file contains bytecode which is equivalent to
source code. Bytecode is not a machine level code. Microprocessor
cannot understand that bytecode. So need of JVM(Java Virtual
Machine). JVM understands the bytecode.
What is the use of JVM?
JVM understands the bytecode. It converts bytecode to machine code.
JVM makes connection with operating system. So it converts bytecode
to machine code which understandable by particular machine or
operating system. After converting in machine code we will get results.
JVM is a program which freely available on internet. Bytecode is a
platform independent but JVM is not. JVM do interaction with processor
and operating system. So JVM is not a platform independent. So if we
have bytecode and want to get result on Windows machine then need
Windows compatible JVM. JVM has different versions for different
operating systems that are freely available on internet.

Another important reason is Java is a secure language. Most of viruses


spread with .exe, .doc, image, audio and video files. Virus can not
spread with text(.txt) files. Java bytecode(.class) file as similar as text
file. So less chances of spread of virus with class files. And JVM also
verify class file before execution. Java is also secure due to lack of
pointors. We can not direct create pointors in java. Pointors makes
chances of unauthorized access of memory.

Conclusion
If we write a java program with X processor and Y operating system then
that program is executable on any other computer system with any
processor and any operating system. So one program or software which
is written in java. It can be execute to any system on internet but it is not
possible with C and C++. Thus java language is the best suitable
language for internet.

Difference Between JDK, JRE and JVM?


Here I try to explain difference between JDK, JRE and JVM. It is a very
basic question asked in many java interviews. I explained it in very basic
manner. These concepts comes under java architecture. It helps to
understand java compilation and execution.

JDK(Java Development Kit) – It includes tools to develop the java


program + JRE.
JRE(Java Runtime Environment) – It includes JVM + Runtime
libraries.
JVM(Java Virtual Machine) – Execute the bytecode.

JDK is used to develop the Java program. It includes javac(java


compiler), appletviewer, javadoc, jar files, javah, jdb etc. It also includes
JRE which gives runtime environment.

JRE provides libraries, java virtual machine and other supporting files to
run applets and applications written in java programming language.

JVM is a purely runtime environment. It executes java bytecode.


Bytecode is a platform independent but JVM is a platform dependent. If
you have bytecode then you can execute that bytecode in any platform
(windows, linux,..). It requires JVM for that particular platform.
Example
Suppose I write a java code in a class “Sample_Demo” and save as
Sample_Demo.java.

javac compile the source code(Sample_Demo.java) and we will get


(Sample_Demo.class) file. “.class” file contains java bytecodes which are
understandable by JVM. Bytecode makes java as a platform
independent language. It makes java code as “Write-Once-Run-
Anywhere“.

How to use Runnable interface for creating Thread in java


How to use Runnable interface for creating Thread in java?
Here is the sample code for implementing Runnable interface for
creating Thread.
Any class can implement runnable interface, so that It can be passed to
thread during thread creation.
1 package com.sampleexamples.threads;
2
public class SimpleRunnableThread implements Runnable {
3
4
@Override
5 public void run() {
6
7 System.out.println("SimpleRunnableThread is starting");
8 for (int i = 1; i <=20; i++) {
9
10
11 //1 second delay code
try {
12 Thread.sleep(1000);
13 } catch (Exception e) {
14 e.printStackTrace();
15 }
16 System.out.println("SimpleRunnableThread will run for "+ (20-i) +" mo
17
18
19 }
20 System.out.println("SimpleRunnableThread is stopping");
21
22 }
23
/**
24 * @param args
25 */
26 public static void main(String[] args) {
27
28 SimpleRunnableThread runnableThread = new SimpleRunnableThread();
29
30 Thread t1 = new Thread(runnableThread);
31
System.out.println("starting t1");
32 t1.start();
33 System.out.println("exiting main ");
34 }
35
36 }
37
38
You can also create multiple thread inside a thread itself.
Another way of creating thread is extending the Thread class.

Switch Case block Sample code in Java


Basic example code for using Switch Case block in your java code.
This example is holding 3 cases along with a default case (when choice
is not belongs to 1,20,10).
1 package com.sampleexamples.basic;
2
public class SwitchBlock {
3
public static void main(String[] args) {
4
5 int choice =10;
6 switch(choice){
7
8 case 1:
9 System.out.println("case 1");
break;
10
11 case 20:
12 System.out.println("case 20");
13 break;
14
15 case 10:
16 System.out.println("case 10");
break;
17
18 default:
19
20
21 System.out.println("default case");
break;
22 }
23
24 }
25 }
26
27
You can also use nested switch case blocks. Switch case block can be
replaced by chained if-else blocks

Nested for loop 2D array sample program


Here is the sample code for nested for loop. In this example I am using
nested for loop for iterating 2D array of integer.
1
2 package com.sampleexamples.basic;
3
4 public class NestedForLoop {
5
6 public static void main(String[] args) {
7
8 int dataArray[][]= {{1,2,3 },
9 {11,12,13 },
{21,22,23 },
10 {31,32,33 }
11 };
12
13 //looping 2D array using nested for loop
14 for(int i=0;i<dataArray.length;i++)
15 {
for (int j = 0; j < dataArray[0].length; j++) {
16 System.out.print(dataArray[i][j]+" ");
17 }
18 //newline
19 System.out.println();
20 }
21
}
22 }
23
24
You can also use nested foreach loops if you are using collections or
arrays.

Foreach loop for String array sample code in Java


Today I am sharing a sample code for foreach loop for looping String
Array.
Here is the sample program code:
1
package com.sampleexamples.basic;
2
3 public class ForEachLoop {
4
5 public static void main(String[] args) {
6
7 String dataArray[]= {"This", "is", "foreach", "example", "text"};
8
9 for(String str:dataArray){
10 System.out.println(str);
}
11
12 }
13
14 }
15
The syntax of foreach loop is little different from regular for loop.

How to store images into database?


Hello friends, here I try to explain how to store images into database. I
discussed steps to insert images into database. It explains with a sample
example. In example, I store an image into Oracle database using Java
programming.

If we want to store images into database then we use BLOB data type to
store images. BLOB(Binary Large Object) is a SQL data type that
represents binary data to be stored into a database. BLOBs used to
store images, audio files or multimedia files.

Steps to store an image into database table


1. Create table with Blob data type. Here I used ImageData column to
store Image.

create table ImageTable(ImageData blob, ImageNo int);

2. First load image into File object.

File ImageFile= new File(“sampleImage.jpg”);

3. Attach the file object to FileInputStream for reading the image.

FileInputStream fis= new FileInputStream(ImageFile);

4. Read the image using FileInputStream and store it into the table using
setBinaryStream() method of Statement interface.
pstmt.setBinaryStream(1,fis,(int)ImageFile.length());
It has 3 parameters.
1 represents First column of ImageTable where the image should be
stored.
fis is a object of FileInputStream that read image.
ImageFile.length() gives ImageFile size in bytes.

pstmt is a object for PreparedStatement we use.

5. Execute the statement using executeUpdate().

pstmt.executeUpdate();

Thus we store image into database.

Java Example to store an image into database


1 // Java Example to store image into Oracle database

import java.sql.*;
2
import java.io.*;
3
public class ImageInsert
4
{
5
public static void main(String[] args)
6
{
7 try
8

9
{
10
Class.forName("oracle.jdbc.driver.OracleDriver");
11
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
12 //Use PreparedStatement to update table. Here table is ImageTable.

13 PreparedStatement pstmt=con.prepareStatement("update ImageTable set I

14 //Load image into file object

15 File ImageFile= new File("sampleImage.jpg");

//Attach the file object to FileInputStream for reading the image.


16
FileInputStream fis= new FileInputStream(ImageFile);
17
//Write the file contents into the table
18
pstmt.setBinaryStream(1,fis,(int)ImageFile.length());
19
//Execute the statement
20
int i=pstmt.executeUpdate();
21

22 System.out.println("No. of records updated = "+i);

23 con.close();

24 }

25 catch (Exception e)

{
26
e.printStackTrace();
27
}
28
}
29
}
30

31

Output
Java File Name: ImageInsert.java
D:\jdk1.7.0_02\bin> javac ImageInsert.java
D:\jdk1.7.0_02\bin> java ImageInsert
No. of records updated = 1

You might also like