0% found this document useful (0 votes)
84 views15 pages

Storing Files in Java Database

The document discusses how to store files and images into a database using Java. It provides steps to create a table with a CLOB or BLOB data type column to store file or image data. It then shows how to load a file or image into a Java File or FileInputStream object, set it to a PreparedStatement using setCharacterStream() or setBinaryStream(), and execute the statement to insert the data into the database table. Sample Java code is provided as an example to insert a text file into an Oracle table using a CLOB and to insert an image into a table using a BLOB.

Uploaded by

ipia0070
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)
84 views15 pages

Storing Files in Java Database

The document discusses how to store files and images into a database using Java. It provides steps to create a table with a CLOB or BLOB data type column to store file or image data. It then shows how to load a file or image into a Java File or FileInputStream object, set it to a PreparedStatement using setCharacterStream() or setBinaryStream(), and execute the statement to insert the data into the database table. Sample Java code is provided as an example to insert a text file into an Oracle table using a CLOB and to insert an image into a table using a BLOB.

Uploaded by

ipia0070
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

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(“[Link]”);

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.
[Link](1,fr,(int)[Link]());

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

4. Execute the statement using executeUpdate().


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

Output
Java file Name: [Link]
D:\jdk1.7.0_02\bin> javac [Link]
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(“[Link]”);

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.
[Link](1,fis,(int)[Link]());
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.
[Link]() gives ImageFile size in bytes.

pstmt is a object for PreparedStatement we use.

5. Execute the statement using executeUpdate().

[Link]();

Thus we store image into database.

Java Example to store an image into database


1 // Java Example to store image into Oracle database
import [Link].*;
2
import [Link].*;
3 public class ImageInsert
4 {
5 public static void main(String[] args)
6 {
7
8
9 try
10 {
11 [Link]("[Link]");
12 Connection con=[Link]("jdbc:oracle:thin:@localho
//Use PreparedStatement to update table. Here table is ImageTable.
13 PreparedStatement pstmt=[Link]("update ImageTable set I
14 //Load image into file object
15 File ImageFile= new File("[Link]");
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 [Link](1,fis,(int)[Link]());
19 //Execute the statement
20 int i=[Link]();
21
22 [Link]("No. of records updated = "+i);
23 [Link]();
}
24 catch (Exception e)
25 {
26 [Link]();
27 }
}
28
}
29
30
31

Output
Java File Name: [Link]
D:\jdk1.7.0_02\bin> javac [Link]
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) [Link]
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


“[Link]“. Java program stores with .java extension. When we
compile it we will get .class extension file. Here we will get
“[Link]” 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 [Link];
2
public class SimpleRunnableThread implements Runnable {
3
4
@Override
5 public void run() {
6
7 [Link]("SimpleRunnableThread is starting");
8 for (int i = 1; i <=20; i++) {
9
10
11 //1 second delay code
try {
12 [Link](1000);
13 } catch (Exception e) {
14 [Link]();
15 }
16 [Link]("SimpleRunnableThread will run for "+ (20-i) +" mo
17
18
19 }
20 [Link]("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
[Link]("starting t1");
32 [Link]();
33 [Link]("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 [Link];
2
public class SwitchBlock {
3
public static void main(String[] args) {
4
5 int choice =10;
6 switch(choice){
7
8 case 1:
9 [Link]("case 1");
break;
10
11 case 20:
12 [Link]("case 20");
13 break;
14
15 case 10:
16 [Link]("case 10");
break;
17
18 default:
19
20
21 [Link]("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 [Link];
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<[Link];i++)
15 {
for (int j = 0; j < dataArray[0].length; j++) {
16 [Link](dataArray[i][j]+" ");
17 }
18 //newline
19 [Link]();
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 [Link];
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 [Link](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(“[Link]”);

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.
[Link](1,fis,(int)[Link]());
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.
[Link]() gives ImageFile size in bytes.

pstmt is a object for PreparedStatement we use.

5. Execute the statement using executeUpdate().

[Link]();

Thus we store image into database.

Java Example to store an image into database


1 // Java Example to store image into Oracle database

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

9
{
10
[Link]("[Link]");
11
Connection con=[Link]("jdbc:oracle:thin:@localho
12 //Use PreparedStatement to update table. Here table is ImageTable.

13 PreparedStatement pstmt=[Link]("update ImageTable set I

14 //Load image into file object

15 File ImageFile= new File("[Link]");

//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
[Link](1,fis,(int)[Link]());
19
//Execute the statement
20
int i=[Link]();
21

22 [Link]("No. of records updated = "+i);

23 [Link]();

24 }

25 catch (Exception e)

{
26
[Link]();
27
}
28
}
29
}
30

31

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

Common questions

Powered by AI

While Java bytecode is platform-independent, the JVM itself is platform-specific because it interacts closely with the underlying operating system and processor to convert bytecode into machine code. Each operating system and processor architecture may have its version of the JVM to ensure proper conversion and execution. Thus, to run Java programs on a particular platform, a JVM compatible with that environment is necessary, allowing the platform-independent bytecode to be executed as machine code suitable for the current hardware and OS .

JDK (Java Development Kit) includes tools for Java program development, such as javac (Java compiler), and other utility tools plus JRE. JRE (Java Runtime Environment) provides libraries and other components necessary to run applications written in Java, including the JVM. JVM (Java Virtual Machine) is the component responsible for converting bytecodes into machine code and executing them. While JDK is used for developing Java applications, JRE provides the environment to execute them. The JVM, which is part of the JRE, performs the actual execution of the Java bytecode. Thus, JDK, JRE, and JVM form a complementary system where the JDK facilitates development and JRE and JVM support executing the resulting programs .

The BLOB (Binary Large Object) data type facilitates the storage of binary files, such as images or multimedia files, by providing a data structure designed to hold large volumes of binary data. The implementation steps in Java are: 1. Create a table with a BLOB column (e.g., create table ImageTable(ImageData blob, ImageNo int);). 2. Load the binary file into a File object (e.g., File ImageFile= new File("sampleImage.jpg")). 3. Attach the file object to a FileInputStream for reading the binary data (e.g., FileInputStream fis= new FileInputStream(ImageFile)). 4. Use the setBinaryStream() method of PreparedStatement to write the binary data into the BLOB column (e.g., pstmt.setBinaryStream(1,fis,(int)ImageFile.length());). 5. Execute the statement with pstmt.executeUpdate().

Java is deemed the most suitable programming language for internet applications primarily due to its platform independence. Java programs compile to bytecode, which can be executed on any system possessing a compatible JVM, making Java adaptable across diverse operating systems like Windows, Linux, and Unix. This attribute ensures consistent execution and results, which is critical for internet applications exposed to a variety of client environments. Additionally, Java's security features, such as the absence of pointers and bytecode verification before execution, contribute to its reliability and security on the Internet .

To store a text file into a database using Java, the following steps are required: 1. Load the text file into a File object (e.g., File TxtFile=new File("sample.txt")). 2. Attach the file object to a FileReader for reading the file data (e.g., FileReader fr=new FileReader(TxtFile)). 3. Use the setCharacterStream() method of PreparedStatement to write the file data into the database column that is of type CLOB (e.g., pstmt.setCharacterStream(1,fr,(int)TxtFile.length());). 4. Execute the update statement using pstmt.executeUpdate(). The CLOB (Character Large Object) data type is used because it is designed to store large text data, allowing the entire content of a text file to be stored within a single column .

One would prefer using the Runnable interface over extending the Thread class in Java when there is a need to implement multiple inheritance, as Java doesn't support it through classes. By implementing the Runnable interface, a class can extend another base class, if needed, while still maintaining the ability to be executed by a thread. This approach also promotes a separation of the task to be performed from the actual thread execution, as the Runnable interface defines a single method run() without implementing methods directly related to thread control .

The JIT (Just-In-Time) compiler is part of the JVM, and it enhances Java program performance by compiling bytecode into native machine code at runtime rather than interpreting it directly. This compilation occurs during program execution, which allows frequently executed bytecodes, known as hotspots, to be optimized for performance. Consequently, the compiled native code runs much faster than interpreted code. The JIT compiler significantly improves Java applications' performance by leveraging runtime information to make optimization decisions that are not possible in static compilation .

The Java Virtual Machine (JVM) is crucial for the execution of Java programs because it converts Java bytecode, which is platform-independent, into machine code that can be executed by the processor. This process includes the use of both an interpreter and a Just-In-Time (JIT) compiler to enhance execution speed. Moreover, the JVM plays a significant role in security by performing bytecode verification; it checks for suspicious code and rejects it if necessary. This verification helps prevent unauthorized access and the execution of malicious code .

Java incorporates several security measures to minimize the risk of malicious code execution, including bytecode verification, the lack of direct pointer manipulation, and automatic memory management. Bytecode verification checks for code integrity and correctness before execution, preventing the execution of code that could cause security breaches. The absence of pointers in Java reduces the risk of unauthorized access to memory and prevents common vulnerabilities like buffer overflows. Automatic garbage collection also ensures that memory is managed in a way that avoids leaks and potential security risks associated with manual memory management. Combined, these features make Java a robust option for secure application development .

The concept of 'Write Once, Run Anywhere' is realized in Java through the use of bytecode, a platform-independent intermediate code generated after a Java program is compiled using the Java compiler (javac). This bytecode is not tied to any particular machine architecture, enabling it to be executed on any device or operating system that has a JVM. The JVM is responsible for interpreting or compiling the bytecode into machine code that's specific to the operating environment, thus enabling the same Java program to run consistently across different platforms. This design abstracts away the hardware and system specifics typically required when programming in languages like C or C++, securely delivering platform independence to developers .

You might also like