这里以一个统计txt文件中每个单词出现的频率的小程序为例子
一、准备工作
1.环境安装
java编译器(这里使用eclipse)
MySQL数据库
2.JDBC驱动包
在网上下载一个JDBC驱动包,然后在项目目录下新建一个“lib”文件夹,将JDBC驱动包放入其中。
然后右键单击驱动包,将鼠标指针悬停在“Build Path”上,点击“Add to Build Path”。
二、加载驱动
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
/*
* 此方法是用来
* 1.加载驱动
* 2.与数据库建立连接
*/
public static Connection getConnection() throws Exception{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/frequency","root","344922992");
} catch (Exception e) {
e.printStackTrace();
//向外抛出异常,谁调用此方法就抛给谁
throw e;
}
return conn;
}
/*
* 3.关闭连接的方法
*/
public static void close(Connection conn){
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Connection conn= getConnection();
System.out.println(conn);
close(conn);
}
}
注意
这一行最后的“frequency”、“root”、“344922992”分别为数据库名称、用户名、密码,这些都要修改成自己的数据库的信息。
这一步成功以后,就意味着java程序已经和MySQL数据库成功连接了。
三、对数据库进行增删改查
import java.sql.Connection;
import java.sql.PreparedStatement;
import util.DBUtil;
/**
* @ClassName: DAO
* @Description: 用来实现对数据库的增删改查
* @author: cyh
* @date: 2018年9月22日 上午11:47:14
*/
public class DAO {
/**
* @Title: save
* @Description: 用来将数据存储在数据库中
* @param word 单词
* @param fre 频率
* @throws Exception void
* @author cyh
* @date 2018年9月22日上午11:47:50
*/
public void save(String word,Integer fre){
Connection conn=null;
PreparedStatement ps=null;
try {
//1.加载驱动并建立连接
conn=DBUtil.getConnection();
String sql="INSERT INTO wordfrequency(word,fre) VALUES(?,?)";
//预编译sql语句
ps=conn.prepareStatement(sql);
//PreparedStatement类中的set方法中的第1个参数
//表示sql语句中第几个问号,第2个参数表示给这个问号赋值
ps.setString(1, word);
ps.setInt(2, fre);
//2.执行sql语句
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
//3.关闭连接
DBUtil.close(conn);
}
}
}
最后附上程序代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import dao.DAO;
/**
* @ClassName: Frequency
* @Description: 统计单词频率
* @author: cyh
*/
public class Frequency{
/**
* @Title: fre
* @Description: 统计单词频率
* @throws IOException void
* @author cyh
*/
public void fre() throws IOException {
File file = new File("test.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));//创建字符流
String line;
String reg = "[,.:\";'?()\\s+\\n]"; //正则表达式
int i = 0;
char[] chars = new char[1024];
TreeMap<String, Integer> tm = new TreeMap<>(); //创建TreeMap对象
while ((i = bf.read(chars)) != -1) {
String s = new String(chars,0,i); //读取文本中的文章内容
Pattern p = Pattern.compile(reg); //创建模式器
Matcher m = p.matcher(s); //创建匹配器
line = m.replaceAll(" ").toLowerCase();//将其他符号替换为空格并改为小写
String[] strs = line.split(" ");//将文章内容由空格分割为字符串数组存入strs
for (String str : strs) { //将strs的元素存入TreeMap对象中
if(!tm.containsKey(str))//如果之前不在TreeMap对象中
tm.put(str,0);//将其存入并置value为0
tm.put(str,tm.get(str)+1);//value加一
}
}
bf.close();
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(tm.entrySet());
Collections.sort(list, (a, b) -> b.getValue() - a.getValue());//排序
DAO dao = new DAO();
list.forEach(itt -> {//将单词和频率存入数据库
try {
dao.save(itt.getKey(), itt.getValue());
} catch (Exception e) {
e.printStackTrace();
}
});
list.forEach(it -> System.out.println(it.getKey()+" "+it.getValue()));//在控制台输出结果
}
public static void main(String[] args) throws IOException {
new Frequency().fre();
}
}
最下面的“test.txt”文件是用来读入原始数据的。