把对象写入Postgresql中
工作中,遇到把大对象写入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中的更多相关文章
- Java基础之序列化对象——将对象写入到文件中(SerializeObjects)
控制台程序. 首先定义一个含有任意不同数据类型域的可序列化类: import java.io.Serializable; public class Junk implements Serializab ...
- PostgreSQL中的索引(一)
引言 这一系列文章主要关注PostgreSQL中的索引. 可以从不同的角度考虑任何主题.我们将讨论那些使用DMBS的应用开发人员感兴趣的事项:有哪些可用的索引:为什么会有这么多不同的索引:以及如何使用 ...
- Postgresql中的large object
1.初识postgresql large object 一位同事在对使用pg_dump备份出来的文件(使用plain格式)进行恢复时,觉得速度非常慢,让我分析一下是什么原因. 我拿到他的.bak文件, ...
- PostgreSQL中定时job执行(pgAgent)
PostgreSQL中定时job执行 业务分析 近期项目需要定期清理数据库中的多余数据,即每月1号删除指定表中一年以上的数据. 初步分析这种定时job可以使用一下两种技术实现: Linux的cront ...
- Java基础知识强化之IO流笔记51:IO流练习之 键盘录入学生信息按照总分排序写入文本文件中的案例
1. 键盘录入学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分排序写入文本文件中 分析: A:创建学生类 B:创建集合对象 TreeSet<Student> ...
- java中将list、map对象写入文件
链接地址:http://blog.sina.com.cn/s/blog_4a4f9fb50101p6jv.html 推荐:凤爪女瓜子男怪象该谁反思伦敦房价为什么持续暴涨 × wvqusrtg个 ...
- PostgreSQL中JSON、JSONB基本操作符
PostgreSQL 9.5以上的版本中有了很多方便的操作符,使得操作 JSON 变得非常方便了. 一. -> 和 ->> : -> 表示获取一个JSON数组元素,支持下标值( ...
- Java将对象保存到文件中/从文件中读取对象
1.保存对象到文件中 Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可: public static void writeObjectToFile(Obje ...
- Postgresql中的数据类型大全
一.数值类型: 下面是PostgreSQL所支持的数值类型的列表和简单说明: 名字 存储空间 描述 范围 smallint 2 字节 小范围整数 -32768 到 +32767 integer 4 字 ...
随机推荐
- HDU 3853 LOOPS 概率DP入门
LOOPS Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)Total Sub ...
- js, lambada? 在chrome和node下可以使用
var a=function(a,c){if(a)c(a)} undefined a(true,(console.log)) VM177:2 Uncaught TypeError: Illegal i ...
- win10易升卸载
- check source code after macro expand
Some time I'd like check source code after macro expand. We can use -E option to stop after the prep ...
- solr6.6安装
1. 确保系统已经安装jdk1.8,以及Tomcat8. 注:使用Tomcat7会出现很多问题,我遇到的是直接打不开solr的index页面,看网上有网友说还会遇到各种css.js资源404..还有l ...
- 点击添加按钮,使用ajax动态添加一行和移除一行,并且序号重新排序和数据不重复操作判断
<div class="control-group " style="top: -20px;position: relative;"> <la ...
- Android Studio 打开后无故爆红后解决办法
今天打开AndroidSutudio后表示一脸蒙蔽,项目无故爆红,我本以为是哪里的代码有错导致 报错,于是乎逐个检查,但是并没有发现任何问题,然后CelarProduct,ReBuildProduct ...
- AC日记——队列安排 洛谷 P1160
队列安排 思路: 链表裸题: 来,上代码: #include <cstdio> #include <cstring> #include <iostream> usi ...
- weblogic优化参数
因部署应用多,内存是使用量较大以及系统需要放在后台运行,以下步骤在确认weblogic可以正常运行的情况下继续进行修改配置. 一.启动免输密码配置: 1.停止weblogic 在系统运行界面按ctrl ...
- Wildcard Matching - LeetCode
Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. ...