DBA Tips Archive for Oracle

  


Load Text Files to BFILE then Write Back Out to Console - (Java)

by Jeff Hunter, Sr. Database Administrator


Contents

  1. Overview
  2. Example



Overview

The following example is part of the Oracle LOB Examples Collection.

This example provides a Java (JDBC) class that demonstrates how to associate two text files with a BFILE column. This example will populate a test table with two records that associate the two text files with a BFILE column. It will then dump the contents of each file to the console.



Example

  • file1.test
  • file2.test

    DROP TABLE test_bfile CASCADE CONSTRAINTS
    /
    
    Table dropped.
    
    
    CREATE TABLE test_bfile (
          id           NUMBER(15)
        , file_name    VARCHAR2(1000)
        , image        BFILE
        , timestamp    DATE
    )
    /
    
    Table created.
    
    
    CREATE OR REPLACE DIRECTORY
        EXAMPLE_LOB_DIR
        AS
        '/u01/app/oracle/lobs'
    /
    
    Directory created.
    
    
    // -----------------------------------------------------------------------------
    // LOBFileExample.java
    // -----------------------------------------------------------------------------
    
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    
    //including this import makes the code easier to read
    import oracle.jdbc.driver.*;
    
    // needed for new BFILE class
    import oracle.sql.*;
    
    /**
     * -----------------------------------------------------------------------------
     * The following class provides an example of dumping the contents of a BFILE.
     *
     * This example creates a DIRECTORY named "EXAMPLE_LOB_DIR" in order to
     * successfully run the tests.
     *
     * IMPORTANT: You will need to create two files named "file1.test" and
     *            "file2.test". The content of the files could be created as follows
     *            in the "EXAMPLE_LOB_DIR" directory.
     *
     *             ------------
     *            | file1.test |
     *            --------------------------------
     *            This is file1.
     *
     *             ------------
     *            | file2.test |
     *            --------------------------------
     *            This is file2.
     *            This a two line file.
     *
     * -----------------------------------------------------------------------------
     */
    
    public class LOBFileExample {
    
        public static void main (String args []) throws Exception {
    
            // Register the Oracle JDBC driver
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    
            String url = "jdbc:oracle:oci8:@TRUESRC_SUNDEV5";
            try {
                String url1 = System.getProperty("JDBC_URL");
                if (url1 != null) {
                    url = url1;
                }
            } catch (Exception e) {
              // If there is any security exception, ignore it and use the default
            }
    
            // Connect to the database
            Connection conn = DriverManager.getConnection (url, "scott", "tiger");
    
            // It's faster when auto commit is off
            conn.setAutoCommit (false);
    
            // Create a Statement
            Statement stmt = conn.createStatement ();
    
    
            try {
                // Create and populate a table with files.
                // The files: "file1" and "file2" must exist in the directory
                //     EXAMPLE_LOB_DIR created above as symbolic name for
                //     /u01/app/oracle/lobs.
    
                stmt.execute(
                        "INSERT INTO test_bfile " +
                        "VALUES (1001, 'file1.test', BFILENAME('EXAMPLE_LOB_DIR', 'file1.test'), sysdate)");
    
                stmt.execute(
                        "INSERT INTO test_bfile " +
                        "VALUES (1002, 'file2.test', BFILENAME('EXAMPLE_LOB_DIR', 'file2.test'), sysdate)");
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
                // An error is raised if the table does not exist. Just ignore it.
            }
    
            // Select the file from the table
            ResultSet rset = stmt.executeQuery ("SELECT * FROM test_bfile");
            while (rset.next ()) {
                String file_name = rset.getString (1);
                BFILE  bfile     = ((OracleResultSet)rset).getBFILE (3);
                System.out.println (file_name + " " + bfile);
    
                // Dump the file contents
                dumpBfile(conn, bfile);
                System.out.println();
            }
    
            // Close all resources
            rset.close();
            stmt.close();
            conn.close();
        }
    
        /*
         * -------------------------------------------------------------------------
         * Utility function to dump the contents of a Bfile
         * -------------------------------------------------------------------------
         */
        static void dumpBfile (Connection conn, BFILE bfile) throws Exception {
    
            System.out.println ("Dumping file : " + bfile.getName());
            System.out.println ("File exists  : " + bfile.fileExists());
            System.out.println ("File open    : " + bfile.isFileOpen());
    
            System.out.println ("Opening File: ");
    
            bfile.openFile();
    
            System.out.println ("File open    : " + bfile.isFileOpen());
    
            long length = bfile.length();
            System.out.println ("File length: " + length);
    
            int chunk = 10;
    
            InputStream instream = bfile.getBinaryStream();
    
            // Create temporary buffer for read
            byte[] buffer = new byte[chunk];
    
            // Fetch data
            while ((length = instream.read(buffer)) != -1) {
    
                System.out.print("Read " + length + " bytes: ");
    
                for (int i=0; i<length; i++) {
                    System.out.print(buffer[i]+" ");
                }
                System.out.println();
            }
    
            // Close input stream
            instream.close();
    
            // close file handler
            bfile.closeFile();
        }
    }
    % javac LOBFileExample.java
    
    % java LOBFileExample
    
    1001 oracle.sql.BFILE@186c6b2
    Dumping file : file1.test
    File exists  : true
    File open    : false
    Opening File:
    File open    : true
    File length: 15
    Read 10 bytes: 84 104 105 115 32 105 115 32 102 105
    Read 5 bytes: 108 101 49 46 10
    
    1002 oracle.sql.BFILE@15ee671
    Dumping file : file2.test
    File exists  : true
    File open    : false
    Opening File:
    File open    : true
    File length: 37
    Read 10 bytes: 84 104 105 115 32 105 115 32 102 105
    Read 10 bytes: 108 101 50 46 10 84 104 105 115 32
    Read 10 bytes: 97 32 116 119 111 32 108 105 110 101
    Read 7 bytes: 32 102 105 108 101 46 10
    


  • Copyright (c) 1998-2017 Jeffrey M. Hunter. All rights reserved.

    All articles, scripts and material located at the Internet address of http://www.idevelopment.info is the copyright of Jeffrey M. Hunter and is protected under copyright laws of the United States. This document may not be hosted on any other site without my express, prior, written permission. Application to host any of the material elsewhere can be made by contacting me at jhunter@idevelopment.info.

    I have made every effort and taken great care in making sure that the material included on my web site is technically accurate, but I disclaim any and all responsibility for any loss, damage or destruction of data or any other property which may arise from relying on it. I will in no case be liable for any monetary damages arising from such loss, damage or destruction.

    Last modified on
    Monday, 23-Jan-2006 08:53:44 EST
    Page Count: 10738