工作中,遇到把大对象写入Postgresql数据库中

package com.geni_sage.gdme.cws.dic;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap; import com.geni_sage.gdme.cws.kuromoji.dict.CharacterDefinition;
import com.geni_sage.gdme.cws.kuromoji.dict.ConnectionCosts;
import com.geni_sage.gdme.cws.kuromoji.dict.Dictionaries;
import com.geni_sage.gdme.cws.kuromoji.dict.TokenInfoDictionary;
import com.geni_sage.gdme.cws.kuromoji.dict.UnknownDictionary;
import com.geni_sage.gdme.cws.kuromoji.trie.DoubleArrayTrie; /**
* 将日语词典写入维护库
*
* @author ywf
*
*/
public class WriteObj2DBTest {
static String pathname = "D:\\yuwenfeng\\T_Miner_TextMing\\gdme\\gdm_agent_start\\mode\\segmentdic\\japanesedic";
static String[] dictionaries = { "tid.dat", "tid_map.dat", "unk.dat",
"unk_map.dat", "cd.dat", "cc.dat", "dat.dat" }; /**
* @param args
* @throws ClassNotFoundException
* @throws IOException
*/
public static void main(String[] args) throws IOException,
ClassNotFoundException {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://127.0.0.1:42856/GDM";
String user = "gsdba";
String password = "gsdba";
if (args.length == 4) {
driver = args[0];
url = args[1];
user = args[2];
password = args[3];
}
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
System.err.println("链接驱动失败");
}
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e1) {
System.err.println("创建连接失败");
}
try {
createTable(con);
write2db(con, dictionaries);
// readfromdb(con, "gs_japanesedic", "tid.dat");
// readfromdb(con, "gs_japanesedic", "tid_map.dat");
// readfromdb(con, "gs_japanesedic", "unk.dat");
// readfromdb(con, "gs_japanesedic", "unk_map.dat");
// readfromdb(con, "gs_japanesedic", "cd.dat");
// readfromdb(con, "gs_japanesedic", "cc.dat");
// readfromdb(con, "gs_japanesedic", "dat.dat");
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 建立日语词典表
*
* @param con
* @throws SQLException
*/
private static void createTable(Connection con) throws SQLException {
String sql = "create table gs_japanesedic(dictype varchar(100),japaninfo bytea)";
Statement stmt = con.createStatement();
stmt.execute(sql);
stmt.close();
} /**
* 把流写入维护库
*
* @param con
* @param path
* @param dicname
* @throws Exception
*/
private static void write2db(Connection con, String[] path)
throws Exception {
CharacterDefinition characterDefinition = UnknownDictionary
.getInstance(pathname).getCharacterDefinition();
short[][] cost = ConnectionCosts.getInstance(pathname).getCosts();
String sql = "insert into gs_japanesedic values(?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
for (int i = 0; i < path.length; i++) {
pstmt.setString(1, path[i]);
byte[] by = null;
if (path[i].equals("cd.dat") || path[i].equals("cc.dat")) {
if (path[i].startsWith("cd")) {// CharacterDefinition
by = getBytes(characterDefinition);
} else {
by = getBytes(cost);// cost
}
} else {
InputStream input = new FileInputStream(pathname + "/"
+ path[i]);
by = getbytes(input);
}
pstmt.setBytes(2, by);
pstmt.addBatch();
}
pstmt.executeBatch();
pstmt.close();
} /**
* convet inputstream into byte[]
*
* @param input
* @return
* @throws IOException
*/
private static byte[] getbytes(InputStream input) throws IOException {
byte[] by = new byte[input.available()];
input.read(by);
return by;
} public static DoubleArrayTrie readtrie(InputStream is) throws IOException {
DoubleArrayTrie trie = new DoubleArrayTrie();
DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
int baseCheckSize = dis.readInt();
int tailSize = dis.readInt();
ReadableByteChannel channel = Channels.newChannel(dis); ByteBuffer tmpBaseBuffer = ByteBuffer.allocateDirect(baseCheckSize * 4);
channel.read(tmpBaseBuffer);
tmpBaseBuffer.rewind();
tmpBaseBuffer.asIntBuffer().asReadOnlyBuffer(); ByteBuffer tmpCheckBuffer = ByteBuffer
.allocateDirect(baseCheckSize * 4);
channel.read(tmpCheckBuffer);
tmpCheckBuffer.rewind();
tmpCheckBuffer.asIntBuffer().asReadOnlyBuffer(); ByteBuffer tmpTailBuffer = ByteBuffer.allocateDirect(tailSize * 2);
channel.read(tmpTailBuffer);
tmpTailBuffer.rewind();
tmpTailBuffer.asCharBuffer().asReadOnlyBuffer(); is.close();
return trie;
} private static void readfromdb(Connection con, String table, String dictype)
throws SQLException, IOException, ClassNotFoundException {
String sql = "select * from " + table + " where dictype = '" + dictype
+ "'";
PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String dic = rs.getString(1);
byte[] by = rs.getBytes(2);
InputStream bi = new ByteArrayInputStream(by);
if (dictype.equals("cd.dat") || dictype.equals("cc.dat")) {
if (dictype.startsWith("cd")) {// CharacterDefinition
CharacterDefinition characterDefinition = (CharacterDefinition) loadObject(bi);
} else {
short[][] cost = (short[][]) loadObject(bi);
} } else if (dictype.startsWith("dat")) {
readtrie(bi);
} else if (dictype.equals("tid.dat") || dictype.equals("unk.dat")) {
loadDictionary(bi);
} else {
loadTargetMap(bi);
}
} } protected static void loadDictionary(InputStream is) throws IOException {
DataInputStream dis = new DataInputStream(is);
int size = dis.readInt();
ByteBuffer tmpBuffer = ByteBuffer.allocateDirect(size);
ReadableByteChannel channel = Channels.newChannel(is);
channel.read(tmpBuffer);
is.close();
tmpBuffer.asReadOnlyBuffer();
} protected static void loadTargetMap(InputStream is) throws IOException,
ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
is));
int[][] targetMap = (int[][]) ois.readObject();
is.close();
} /**
* 根据序列化对象得到byte[]
*
* @param obj
* @return
* @throws IOException
*/
public static byte[] getBytes(Serializable obj) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(obj);
out.flush();
byte[] bytes = bout.toByteArray();
bout.close();
out.close();
return bytes;
} public static Object getObject(byte[] bytes) throws IOException,
ClassNotFoundException {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
Object obj = oi.readObject();
bi.close();
oi.close();
return obj;
} public static Object loadObject(InputStream in) throws IOException,
ClassNotFoundException {
ObjectInputStream oi = new ObjectInputStream(in);
Object obj = oi.readObject();
in.close();
oi.close();
return obj;
}
}

把对象写入Postgresql中的更多相关文章

  1. Java基础之序列化对象——将对象写入到文件中(SerializeObjects)

    控制台程序. 首先定义一个含有任意不同数据类型域的可序列化类: import java.io.Serializable; public class Junk implements Serializab ...

  2. PostgreSQL中的索引(一)

    引言 这一系列文章主要关注PostgreSQL中的索引. 可以从不同的角度考虑任何主题.我们将讨论那些使用DMBS的应用开发人员感兴趣的事项:有哪些可用的索引:为什么会有这么多不同的索引:以及如何使用 ...

  3. Postgresql中的large object

    1.初识postgresql large object 一位同事在对使用pg_dump备份出来的文件(使用plain格式)进行恢复时,觉得速度非常慢,让我分析一下是什么原因. 我拿到他的.bak文件, ...

  4. PostgreSQL中定时job执行(pgAgent)

    PostgreSQL中定时job执行 业务分析 近期项目需要定期清理数据库中的多余数据,即每月1号删除指定表中一年以上的数据. 初步分析这种定时job可以使用一下两种技术实现: Linux的cront ...

  5. Java基础知识强化之IO流笔记51:IO流练习之 键盘录入学生信息按照总分排序写入文本文件中的案例

    1.  键盘录入学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分排序写入文本文件中 分析:   A:创建学生类   B:创建集合对象      TreeSet<Student>   ...

  6. java中将list、map对象写入文件

    链接地址:http://blog.sina.com.cn/s/blog_4a4f9fb50101p6jv.html     推荐:凤爪女瓜子男怪象该谁反思伦敦房价为什么持续暴涨 × wvqusrtg个 ...

  7. PostgreSQL中JSON、JSONB基本操作符

    PostgreSQL 9.5以上的版本中有了很多方便的操作符,使得操作 JSON 变得非常方便了. 一. -> 和 ->> : -> 表示获取一个JSON数组元素,支持下标值( ...

  8. Java将对象保存到文件中/从文件中读取对象

    1.保存对象到文件中 Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可: public static void writeObjectToFile(Obje ...

  9. Postgresql中的数据类型大全

    一.数值类型: 下面是PostgreSQL所支持的数值类型的列表和简单说明: 名字 存储空间 描述 范围 smallint 2 字节 小范围整数 -32768 到 +32767 integer 4 字 ...

随机推荐

  1. MongoDB如何使用“”用户名和密码“”

    在去年的 DB 勒索事件之后, 不少的同学开始加强 Mongodb 的安全性, 其中一种办法就是设置复杂的密码. 那么问题来了, 如果设置的密码里包含一些如 “@”, “:” 一样的特殊字符怎么办? ...

  2. 【Visual Studio】无法打开包括文件:“SDKDDKVer.h”

    解决办法是在头文件的搜索目录中添加$(WindowsSDK_IncludePath);,同时在库文件的搜索目录中添加$(WindowsSDK_LibraryPath_x86);

  3. hdu 5475(打破固定思维OR线段树)

    An easy problem Time Limit: 8000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)T ...

  4. Ubuntu 16.04下使用Wine安装Notepad++

    说明: 1.使用的Wine版本是深度出品(Deepin),已经精简了很多没用的配置,使启动能非常快,占用资源小. 2.关于没有.wine文件夹的解决方法:在命令行上运行winecfg: 下载: (链接 ...

  5. php设置报错级别

    ini_set("display_errors", "On");//若页面不报错的话,请设置php.ini 的display_errors 为 On error ...

  6. 任务驱动,对比式学习.NET开发系列之开篇------开源2个小框架(一个Winform框架,一个Web框架)

    一 源码位置 1. Winform框架 2. web框架 二 高效学习编程的办法 1 任务驱动方式学习软件开发 大部分人学习软件开发技术是通过看书,看视频,听老师上课的方式.这些方式有一个共同点即按知 ...

  7. delphi中如何将string类型的字符串数据转化成byte[]字节数组类型的数据

    var  S:String;  P:PChar;  B:array of Byte;begin  S:='Hello';  SetLength(B,Length(S)+1);  P:=PChar(S) ...

  8. lock与monitor的区别

    1.Lock 只能对引用对象加锁 Lock锁定区间内可以对锁定值修改而不发生运行时错误,通常也会采用此种修改方式.这种方式又有点类同于使用Monitor.Wait取得资源,并对这个资源进行操作. 用法 ...

  9. 检查iOS app 是否升级为新版本

    之前我帮某公司做的一个iOS app,升级的时候发现闪退问题.后来检查是因为升级的时候数据库出现一点小问题导致对象为空. 下面这个代码可以检测程序是否更新了,从而进行相关处理: 1 2 3 4 5 6 ...

  10. Define Custom Data Filter Using Pre-Query Trigger In Oracle Forms

    Oracle Forms is having its default records filter, which we can use through Enter Query mode to spec ...