【测试常用小工具】文件读取进行解析输入需要信息
public static void transformToWords() throws Exception { // 连接数据库 DB db = new DB(); Connection con = db.getConnection(); Statement stmt = null; ResultSet rs = null; try { BufferedReader in = new BufferedReader(new FileReader( "d://TestTry//yuan.txt")); PrintWriter out = new PrintWriter("d://TestTry//test.txt"); String num; String sql; String strLemma = null; // 增加事务操作 con.setAutoCommit(false); // 数据处理 while ((num = in.readLine()) != null) { stmt = con.createStatement(); sql = "select lemma from words where index_word_id = " + num; rs = stmt.executeQuery(sql); while (rs.next()) { strLemma = rs.getString("lemma"); } // 写入文件 out.append(strLemma + "\n"); rs.close(); stmt.close(); } con.commit(); out.close(); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } db.closeConnection(con); System.out.println("OK"); }
主要是实现了从一个文件里读取一行里的文字,进行数据库里搜索进行匹配,然后再重新读取到新的文件里即可。
下面是DB文件:
public class DB { public static String dbtype = ""; /**********************************************************************************************/ // 连接跟关闭数据库 /* * @return 返回数据库连接,Connection对象 */ public Connection getConnection() { Connection conn = null; try { String ip ="112.124.114.203"; // 连接JDBC数据源 String sqlDriver = "com.mysql.jdbc.Driver"; String connectionString ="jdbc:mysql://localhost:3306/wordtest?useunicode=true&characterEncoding=UTF-8"; String username = "root"; String password = ""; Class.forName(sqlDriver).newInstance(); conn = DriverManager.getConnection(connectionString, username, password); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return conn; } /* * 关闭数据库连接对象 */ public void closeConnection(Connection conn) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }