01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.samples;
07:
08: import java.io.IOException;
09: import java.io.RandomAccessFile;
10: import java.sql.Connection;
11: import java.sql.DriverManager;
12: import java.sql.ResultSet;
13: import java.sql.Statement;
14:
15: /**
16: * This sample application shows how to create a user defined function
17: * to read a file from the file system.
18: */
19: public class FileFunctions {
20:
21: public static void main(String[] args) throws Exception {
22: Class.forName("org.h2.Driver");
23: Connection conn = DriverManager.getConnection("jdbc:h2:mem:",
24: "sa", "");
25: Statement stat = conn.createStatement();
26: stat
27: .execute("CREATE ALIAS READ_TEXT_FILE FOR \"org.h2.samples.FileFunctions.readTextFile\" ");
28: stat
29: .execute("CREATE ALIAS READ_TEXT_FILE_WITH_ENCODING FOR \"org.h2.samples.FileFunctions.readTextFileWithEncoding\" ");
30: stat
31: .execute("CREATE ALIAS READ_FILE FOR \"org.h2.samples.FileFunctions.readFile\" ");
32: ResultSet rs = stat.executeQuery("CALL READ_FILE('test.txt')");
33: rs.next();
34: byte[] data = rs.getBytes(1);
35: System.out.println("length: " + data.length);
36: rs = stat.executeQuery("CALL READ_TEXT_FILE('test.txt')");
37: rs.next();
38: String text = rs.getString(1);
39: System.out.println("text: " + text);
40: conn.close();
41: }
42:
43: /**
44: * Read a String from a file. The default encoding for this platform is used.
45: *
46: * @param fileName the file name
47: * @return the text
48: */
49: public static String readTextFile(String fileName)
50: throws IOException {
51: byte[] buff = readFile(fileName);
52: String s = new String(buff);
53: return s;
54: }
55:
56: /**
57: * Read a String from a file using the specified encoding.
58: *
59: * @param fileName the file name
60: * @param encoding the encoding
61: * @return the text
62: */
63: public static String readTextFileWithEncoding(String fileName,
64: String encoding) throws IOException {
65: byte[] buff = readFile(fileName);
66: String s = new String(buff, encoding);
67: return s;
68: }
69:
70: /**
71: * Read a file into a byte array.
72: *
73: * @param fileName the file name
74: * @return the byte array
75: */
76: public static byte[] readFile(String fileName) throws IOException {
77: RandomAccessFile file = new RandomAccessFile(fileName, "r");
78: try {
79: byte[] buff = new byte[(int) file.length()];
80: file.readFully(buff);
81: return buff;
82: } finally {
83: file.close();
84: }
85: }
86: }
|