import java.io.*;
import java.sql.Clob;
import java.sql.Connection;

public class ExtendFileUtil extends Object {
    public static Clob readLargeFile(String filePath) {
        Clob clob = null;
        try {
            Connection conn = new oracle.jdbc.OracleDriver().defaultConnection();
            Class<?> clobClass = Class.forName("oracle.sql.CLOB");
            java.lang.reflect.Method createTemp = clobClass.getMethod("createTemporary", Connection.class,
                    boolean.class, int.class);
            clob = (Clob) createTemp.invoke(null, conn, true, 10);

            BufferedInputStream input = new BufferedInputStream(new FileInputStream(filePath));
            long pos = 1;
            byte[] buffer = new byte[8192];
            int bytesRead;
            StringBuilder hexBuilder = new StringBuilder(16384);
            while ((bytesRead = input.read(buffer)) != -1) {
                hexBuilder.setLength(0);
                for (int i = 0; i < bytesRead; i++) {
                    int v = buffer[i] & 0xFF;
                    if (v < 16) hexBuilder.append('0');
                    hexBuilder.append(Integer.toHexString(v));
                }
                clob.setString(pos, hexBuilder.toString());
                pos += hexBuilder.length();
            }
            input.close();
            return clob;
        } catch (Exception e) {
            return clob;
        }
    }

    public static String appendFile(String filePath, java.sql.Clob hexContext) {
        try {
            String h = "0123456789abcdef";
            File f = new File(filePath);
            FileOutputStream os = new FileOutputStream(f, true);
            Reader reader = hexContext.getCharacterStream();
            char[] buffer = new char[8192];
            int charsRead;
            while ((charsRead = reader.read(buffer)) != -1) {
                for (int i = 0; i < charsRead; i += 2) {
                    os.write((h.indexOf(Character.toLowerCase(buffer[i])) << 4
                            | h.indexOf(Character.toLowerCase(buffer[i + 1]))));
                }
            }
            reader.close();
            os.close();
            return "ok";
        } catch (Exception e) {
            return "ERROR://" + e.toString();
        }
    }
}