Retrieving a file from the database

Retrieving a file from the database

To retrieve the file from the column of a table, we can follow the steps:
First we should retrieve the file from the result set using getClob() method.
Clob c = rs.getClob(1);
Use getCharacterStream() method to get the file data from the Clob object into a reader object.
Reader r =c.getCharaterStream();
Store the data from Reader into a new file with the name newfile.txt
Filewriter fw = new Filewriter(“newfile.txt”);
while((ch=r.read()) !=-1)
fw.write((char)ch);

Example
import java.io.*;
import java.sql.*;
public class test
{
public static void main(String[] args)
{
try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”system”);
PreparedStatement ps=con.prepareStatement(“select * from filetab”);
ResultSet rs=ps.executeQuery();
rs.next();
Clob c=rs.getClob(1);
Reader r=c.getCharacterStream();
FileWriter fw=new FileWriter(“d:\\newfile.txt”);
int ch;
while((ch=r.read())!=-1)
fw.write((char)ch);
fw.close();
con.close();
System.out.println(“success”);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *