H2資料庫儲存檔案?

H2資料庫快速、小巧、Java語言編寫,眾多優點,所以在使用本地資料庫時,我選擇了H2.

需求:用H2資料庫儲存大資料——檔案。

工具/原料

H2

方法/步驟

H2資料庫的資料型別,見下圖。這些型別基本和其他資料庫的型別差不多,之所以要寫這個經驗,是因為我用到了它的CLOB型別。下面介紹一下CLOB怎麼使用。

H2資料庫儲存檔案

BLOB主要用於儲存像檔案或者圖片這樣的大資料。CLOB主要用於XML、HTML、Txt檔案等。

H2資料庫儲存檔案

H2資料庫儲存檔案

現在的需求是表中某一列存放檔案資料,檔案內容通過Base64編碼儲存。

H2資料庫儲存檔案

存入資料庫時,我是將檔案內容通過Base64編碼存入的字串。

import org.apache.commons.codec.binary.Base64;

public static String getBase64StringFromFile(File file) {

String result = "";

try {

InputStream is = new FileInputStream(file);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int ch ;

while((ch = is.read()) != -1) {

baos.write(ch);

}

byte[] bs = baos.toByteArray();

result = Base64.encodeBase64String(bs);

is.close();

baos.close();

} catch (IOException e) {

logger.debug(e.getLocalizedMessage());

}

return result;

}

這裡的result就是Base64編碼後的字串了。

H2資料庫儲存檔案

從資料庫中讀出來時,該列資料型別是CLOB,那怎麼再顯示這個檔案呢?

Clob clob = (Clob) objs[0][14];

BufferedReader br = (BufferedReader) clob.getCharacterStream();

StringBuilder sb = new StringBuilder();

String rline = null;

while ((rline = br.readLine()) != null) {

sb.append(rline);

}

String content = sb.toString();

這個content就是上步說的Base64編碼後的字串。

如果要還原該檔案,還需要再Base64解碼後再儲存成檔案。

public static boolean getFileFromBase64String(String base64Str , String filePath) {

byte[] bs = Base64.decodeBase64(base64Str);

FileOutputStream fos = null;

try {

File f = new File(filePath);

if(!f.exists())

f.createNewFile();

fos = new FileOutputStream(f);

fos.write(bs);

fos.close();

return true;

} catch (FileNotFoundException e) {

logger.debug(e.getLocalizedMessage());

} catch (IOException e) {

logger.debug(e.getLocalizedMessage());

}

return false;

}

這裡的filePath就是我們還原之後的檔案的路徑,就可以看到還原後的檔案了。

H2資料庫儲存檔案

至此,應該對CLOB型別有了一定了解了,知道如何使用了吧。

注意事項

如果有什麼不懂的可以留言

資料, 檔案, 資料庫, 語言, 優點,
相關問題答案