1 5 package org.h2.samples; 6 7 import java.io.IOException ; 8 import java.io.RandomAccessFile ; 9 import java.sql.Connection ; 10 import java.sql.DriverManager ; 11 import java.sql.ResultSet ; 12 import java.sql.Statement ; 13 14 public class FileFunctions { 15 16 public static void main(String [] args) throws Exception { 17 Class.forName("org.h2.Driver"); 18 Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", ""); 19 Statement stat = conn.createStatement(); 20 stat.execute("CREATE ALIAS READ_TEXT_FILE FOR \"org.h2.samples.FileFunctions.readTextFile\" "); 21 stat.execute("CREATE ALIAS READ_TEXT_FILE_WITH_ENCODING FOR \"org.h2.samples.FileFunctions.readTextFileWithEncoding\" "); 22 stat.execute("CREATE ALIAS READ_FILE FOR \"org.h2.samples.FileFunctions.readFile\" "); 23 ResultSet rs = stat.executeQuery("CALL READ_FILE('test.txt')"); 24 rs.next(); 25 byte[] data = rs.getBytes(1); 26 System.out.println("length: " + data.length); 27 rs = stat.executeQuery("CALL READ_TEXT_FILE('test.txt')"); 28 rs.next(); 29 String text = rs.getString(1); 30 System.out.println("text: " + text); 31 conn.close(); 32 } 33 34 public static String readTextFile(String fileName) throws IOException { 35 byte[] buff = readFile(fileName); 36 String s = new String (buff); 37 return s; 38 } 39 40 public static String readTextFileWithEncoding(String fileName, String encoding) throws IOException { 41 byte[] buff = readFile(fileName); 42 String s = new String (buff, encoding); 43 return s; 44 } 45 46 public static byte[] readFile(String fileName) throws IOException { 47 RandomAccessFile file = new RandomAccessFile (fileName, "r"); 48 try { 49 byte[] buff = new byte[(int)file.length()]; 50 file.readFully(buff); 51 return buff; 52 } finally { 53 file.close(); 54 } 55 } 56 } 57 | Popular Tags |