Monday, February 9, 2009

Program in Java to convert physical files in jpg format to Binary files in Oracle Database

Connection to Oracle database

import java.sql.*;
import java.sql.Connection;

public class Conn {
static String url = "jdbc:oracle:thin:@ipaddress:1521:dbname";

static String user = "username";

static String pass = "password";

public static Connection getConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, user, pass);
return conn;

} catch (Exception ms) {
ms.printStackTrace();
return null;
}
}

public static void main(String ss[]) {
Connection conn = Conn.getConnection();
}

}

Create binary files


import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

class MySignFilter implements FileFilter {
public boolean accept(File pathname) {
return (pathname.getName().toLowerCase().endsWith("jpg"));
}
}

public class Transfer {

Connection conn = Conn.getConnection();

public void ReadFile() {

try {
File chkerror = new File("C:/pic/errfile.txt");
chkerror.setWritable(true);
FileWriter writer = new FileWriter(chkerror);
PrintWriter printwriter = new PrintWriter(writer);
File file = new File("C:/pic");
MySignFilter mySign = new MySignFilter();
File list[] = file.listFiles(mySign);

for (int i = 0; i < list.length; i++) {

FileInputStream ins = new FileInputStream(list[i]);
byte b[] = new byte[ins.available()];
System.out.println(i+ ":"+ list[i].getName().trim().toLowerCase().replace(".jpg", ""));
if (b.length < 65536) {

PreparedStatement ps = conn
.prepareStatement("insert into binfiles "
+ " (fname,fvalue) "
+ " values (?,?)");
ps.setString(1, list[i].getName().trim().toLowerCase().replace(".jpg", ""));
ps.setBinaryStream(2, ins, (int) list[i].length());
ps.executeUpdate();
ps.close();
ins.close();
conn.commit();

} else {
printwriter.append(list[i].getName().trim() + "\n");
}

}
printwriter.flush();
printwriter.close();
writer.close();

} catch (Exception ms) {
ms.printStackTrace();
}
}

public static void main(String args[]) {
Transfer trn = new Transfer();
trn.ReadFile();
}

}

No comments: