how to Fix JAVA error NullPointerException(with jdbc) [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I do not speak English well
An error occurred while doing JDBC.
I knew during coding that ' executequery ' should only be done by ' select ' in the database, and ' insert ' should be ' executeupdate '.
However, when I did executeupdate, I had a problem with the variable and changed it to " int "
Then an error occurred.
How can it be carried out as I intended?
I'll show you the code.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class EdgeCloud {
static ArrayList<String> deleteDB = new ArrayList<>();
static ArrayList<String> DBCarIP = new ArrayList<>();
static ArrayList<String> ContainerCarIP = new ArrayList<>();
static String carSSID = "192.0.1";
static String state;
static String upDateInputContainer;
static String upDateInputCar;
static int i = 0;
static String cIP;
//-------------------------------------------( main start )----------------------------------------------------//
public static void main(String[] args) throws Exception {
System.out.println("main start");
while(true) {
// JDBC(state="check");
if(carSSID!=null) {
makeContainer();
}else {
UPDATE();
}
}
}
//-------------------------------------------( main end )----------------------------------------------------//
//-------------------------------------------( make container start )----------------------------------------------------//
public static void makeContainer() throws Exception {
System.out.println("mc start");
String makeContainer = "/usr/local/bin/docker run --name "+carSSID+" ubuntu:16.04";
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(makeContainer);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
String ipload = "/usr/local/bin/docker inspect -f {{.NetworkSettings.IPAddress}} "+carSSID;
IPLoad(ipload);
}
//-------------------------------------------( make container end )----------------------------------------------------//
//-------------------------------------------( get container ip start )----------------------------------------------------//
public static void IPLoad(String ipload) throws Exception {
System.out.println("ipload start");
upDateInputCar = null;
upDateInputContainer = null;
upDateInputCar = carSSID;
carSSID = null;
state = "insert";
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(ipload);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while((cIP = br.readLine()) != null) {
upDateInputContainer= cIP;
System.out.println("cip : "+cIP);
}
System.out.println("upd"+upDateInputContainer);
JDBC(state);
}
//-------------------------------------------( get container ip end )----------------------------------------------------//
//-------------------------------------------( update start )----------------------------------------------------//
public static void UPDATE() throws Exception {
state = "check";
JDBC(state);
String getContainerName = "/usr/local/bin/docker ps --format {{.Names}}";
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(getContainerName);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
ContainerCarIP.add(line);
}
deleteDB.addAll(DBCarIP);
deleteDB.removeAll(ContainerCarIP);
if(deleteDB.get(0)!=null) {
state="delete";
while(deleteDB.get(i++)!=null) {
//JDBC(state);
}
i = 0;
}
}
//-------------------------------------------( update end )----------------------------------------------------//
//-------------------------------------------( socket start )----------------------------------------------------//
/*socket place
-
-
-
-
-
-
*/
//-------------------------------------------( soket end )----------------------------------------------------//
//-------------------------------------------( JDBC start )----------------------------------------------------//
public static void JDBC(String state){
System.out.println("JDBC start");
Connection conn = null ;
Statement stmt = null;
String query = null;
if(state=="insert") {
query = "insert into inpo (ip, carid) values ('"+upDateInputContainer+"', '"+upDateInputCar+"')";
System.out.println(query);
}
if(state=="delete") {
query = "delete from inpo where carid = " +deleteDB.get(i);
}
if(state=="check") {
query = "select carid from inpo";
}
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
}
catch(ClassNotFoundException e ){
System.out.println( "드라이버 연결 에러." ) ;
}
catch(Exception etc) {
System.out.println(etc.getMessage());
}
try{
// String url = "jdbc:mysql://192.168.44.122:3306/ssidIp?serverTimezone=UTC&autoReconnect=true&useSSL=false";
String url = "jdbc:mysql://localhost:3306/ssidIp?serverTimezone=UTC&autoReconnect=true&useSSL=false";
String userPass = "123456789" ;
conn = DriverManager.getConnection(url, userId, userPass);
stmt = conn.createStatement();
ResultSet rs = null;
int rss = 0;
if(state=="check") {
rs = stmt.executeQuery(query);
}else {
rss = stmt.executeUpdate(query);
}//////////////////////////////////////////////////////
if (state=="check") {
rs = stmt.getResultSet();
}
System.out.println("------------------------------------");
System.out.println("debug1 ");
if(state=="check") {
System.out.println("debug 2");
while (rs.next()) {
String str = rs.getNString(1);
DBCarIP.add(str);
}
}else {
System.out.println("debug 3");
while(rs.next()) { // here NullpointerException
System.out.println("debug 4");
String str = rs.getNString(1);
System.out.println(str);
}
}
System.out.println("연결");
stmt.close();
conn.close();
}
catch( SQLException e ){
System.out.println( "SQLException : " + e.getMessage() ) ;
}
}
}
//-------------------------------------------( JDBC end )----------------------------------------------------//
ERROR part
main start
mc start
ipload start
cip : 172.17.0.3
upd172.17.0.3
JDBC start
insert into inpo (ip, carid) values ('172.17.0.3', '192.0.1')
------------------------------------
debug1
debug 3
Exception in thread "main" java.lang.NullPointerException
at edgeCloud.EdgeCloud.JDBC(EdgeCloud.java:195)
at edgeCloud.EdgeCloud.IPLoad(EdgeCloud.java:86)
at edgeCloud.EdgeCloud.makeContainer(EdgeCloud.java:61)
at edgeCloud.EdgeCloud.main(EdgeCloud.java:33)

You’re reading from rs instead of rss but rs is null for an insert or delete query.
else {
System.out.println("debug 3");
while(rs.next()) {
System.out.println("debug 4");
String str = rs.getNString(1);
System.out.println(str);
}
}
You need to change this to something like this since rss will contain the number of rows inserted or deleted.
else {
System.out.println("debug 3");
if (rss > 0) {
System.out.println("debug 4");
//...
}

Related

Apache DBCP and Oracle Transparent Application continuity

We have an older application that can't failover when one node of our Oracle RAC goes down. It seems it uses an older version of org.apache.commons.dbcp.BasicDataSource. I can make this work when I use UCP from Oracle but when I use the apache version the app dies as soon as I shut down the node of the RAC it is connected to. Am I missing something or does it not work with Apache DBCP? Thanks
Here is my code.
import org.apache.commons.dbcp.BasicDataSource;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BasicDB{
final static String DB_URL ="jdbc:oracle:thin:user/password#pdb_tac";
final static String driverClassName = "oracle.jdbc.replay.OracleDataSourceImpl";
private void pressAnyKeyToContinue()
{
System.out.print("Press any key to continue...");
try { System.in.read(); }
catch(Exception e) { e.printStackTrace(); }
}
public String getInstanceName(Connection conn) throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("select instance_name from v$instance");
String r = new String();
for(ResultSet result = pstmt.executeQuery(); result.next(); r = result.getString("instance_name")) {
}
pstmt.close();
return r;
}
private void doTx(Connection c, int numValue) throws SQLException {
String updsql = "UPDATE test SET v=UPPER(v) WHERE id=?";
PreparedStatement pstmt = null;
pstmt = c.prepareStatement(updsql);
c.setAutoCommit(false);
for(int i = 0; i < numValue; ++i) {
pstmt.setInt(1, i);
pstmt.executeUpdate();
}
c.commit();
pstmt.close();
}
public static void main(String[] args) throws SQLException {
Connection conn = null;
int numValue = 5000;
;
try {
BasicDataSource bods = new BasicDataSource();
bods.setUrl(DB_URL);
bods.setDriverClassName(driverClassName);
bods.setDefaultAutoCommit(false);
BasicDB self = new BasicDB();
conn = bods.getConnection();
String var10001 = self.getInstanceName(conn);
var10000.println("Instance Name = " + var10001);
System.out.println("Performing transactions");
self.pressAnyKeyToContinue();
self.doTx(conn, numValue);
var10001 = self.getInstanceName(conn);
var10000.println("Instance Name = " + var10001);
} catch (Exception var8) {
var8.printStackTrace();
}
}
}
Ok, so it has to do with using the DataSource instead of the DataDriver class. I have run into another error so will create a new question for that.

compare filename to an integer

I have a database in mysql with field userId, userName etc,. from here I'm retrieving userid based on some criteria.
I have a folder with files and name of the file is some userId . I want to compare retrieved userId with those files and if they match further process those files.
I tried this code but its giving number format exception. not able to understand why?
package read;
import java.io.*;
import java.util.*;
import java.sql.*;
public class read1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
static final String USER = "root";
static final String PASS = "root";
public static void main(String args[])throws Exception{
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT userId FROM profile1 where friendCount >200 AND statusCount > 200";
ResultSet rs = stmt.executeQuery(sql);
processing p = new processing();
File directory = new File("/home/abc/tweet");
//get all the files from a directory
File[] fList = directory.listFiles();
while(rs.next()){
int uid = rs.getInt("userId");
System.out.print("ID: " + uid +"\n");
for (File file : fList){
if(file.isFile())
System.out.println(file.getName());
if(Integer.parseInt(file.getName())== uid)
p.process(file.getName());
}
}
}
catch(SQLException e){
e.printStackTrace();
}
}
}
class processing{
void process(String filename)throws Exception{
FileReader fr = new FileReader("/home/abc/tweet/"+filename);
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("/home/abc/newtweet/"+filename);
String s;
String str="Text:";
String a[];
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
if (s.startsWith("Text:")) { // worked
a= s.split(" ");
for(int k=1;k<a.length;k++)
bw.write(a[k]+"\n"); // worked
}
}
br.close();
bw.close();
}
}
One reason could be that there are also other files in the folder /home/abc/tweet/ with names that cant be parsed as an Integer.

How to make semicolon (;) as delimiter in java

I made a program that can parse .csv file to database,
I want to make semicolon as delimiter but I got some trouble here ~
This is my code CSVLoader.java
package id.co.lolo.coreservice;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import au.com.bytecode.opencsv.CSVReader;
public class CSVLoader {
private static final String SQL_INSERT = "INSERT INTO ${table}(${keys}) VALUES(${values})";
private static final String TABLE_REGEX = "\\$\\{table\\}";
private static final String KEYS_REGEX = "\\$\\{keys\\}";
private static final String VALUES_REGEX = "\\$\\{values\\}";
private Connection connection;
private char seprator;
/**
* Public constructor to build CSVLoader object with Connection details. The
* connection is closed on success or failure.
*
* #param connection
*/
public CSVLoader(Connection connection) {
this.connection = connection;
// Set default separator
this.seprator = ',';
}
/**
* Parse CSV file using OpenCSV library and load in given database table.
*
* #param csvFile
* Input CSV file
* #param tableName
* Database table name to import data
* #param truncateBeforeLoad
* Truncate the table before inserting new records.
* #throws Exception
*/
#SuppressWarnings("resource")
public void loadCSV(String csvFile, String tableName,
boolean truncateBeforeLoad) throws Exception {
CSVReader csvReader = null;
if (null == this.connection) {
throw new Exception("Not a valid connection.");
}
try {
csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error occured while executing file. "
+ e.getMessage());
}
String[] headerRow = csvReader.readNext();
if (null == headerRow) {
throw new FileNotFoundException(
"No columns defined in given CSV file."
+ "Please check the CSV file format.");
}
String questionmarks = StringUtils.repeat("?,", headerRow.length);
questionmarks = (String) questionmarks.subSequence(0,
questionmarks.length() - 1);
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
query = query
.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
query = query.replaceFirst(VALUES_REGEX, questionmarks);
System.out.println("Query: " + query);
String[] nextLine;
Connection con = null;
PreparedStatement ps = null;
try {
con = this.connection;
con.setAutoCommit(false);
ps = con.prepareStatement(query);
if (truncateBeforeLoad) {
// delete data from table before loading csv
con.createStatement().execute("DELETE FROM " + tableName);
}
final int batchSize = 1000;
int count = 0;
Date date = null;
while ((nextLine = csvReader.readNext()) != null) {
if (null != nextLine) {
int index = 1;
for (String string : nextLine) {
date = DateUtil.convertToDate(string);
if (null != date) {
ps.setDate(index++,
new java.sql.Date(date.getTime()));
} else {
ps.setString(index++, string);
}
}
ps.addBatch();
}
if (++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
con.commit();
} catch (Exception e) {
con.rollback();
e.printStackTrace();
throw new Exception(
"Error occured while loading data from file to database."
+ e.getMessage());
} finally {
if (null != ps)
ps.close();
if (null != con)
con.close();
csvReader.close();
}
}
public char getSeprator() {
return seprator;
}
public void setSeprator(char seprator) {
this.seprator = seprator;
}
}
this is Main.java
package id.co.lolo.coreservice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
#SuppressWarnings("unused")
private static String JDBC_CONNECTION_URL =
"jdbc:mysql://localhost:3306/bni";
public static void main(String[] args) {
try {
CSVLoader loader = new CSVLoader(getCon());
loader.setSeprator(';');
loader.loadCSV("C:\\Log\\Logtima.csv", "coreservice", true);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection getCon() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bni","root","shikamaru");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
I got this Error,
Query: INSERT INTO coreservice(MODULE_NAME,SERVICE_NAME,COUNTER,LOG_DATE,UPDATE_DATE) VALUES(?)
java.sql.BatchUpdateException: Column count doesn't match value count at row 1
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1693)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1108)
at id.co.bni.coreservice.CSVLoader.loadCSV(CSVLoader.java:118)
at id.co.bni.coreservice.Main.main(Main.java:20)
java.lang.Exception: Error occured while loading data from file to database.Column count doesn't match value count at row 1
at id.co.bni.coreservice.CSVLoader.loadCSV(CSVLoader.java:123)
at id.co.bni.coreservice.Main.main(Main.java:20)

Switching to specific window using PID (Process ID)

I'm working on a Java Selenium program which uses Runtime class.
There are multiple instances of Internet Explorer windows that are open.
I need to "Bring Front" only one specific window for the selenium suite to run without errors.I have retrieved the specific iexplore instance using tasklist command.
Now I have the PID of the process.
Process p = Runtime.getRuntime().exec("tasklist /FI \"WindowTitle eq Google\"");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
int count=1;
while ((line = in.readLine()) != null) {
System.out.println(count + " " + line);
count++;
}
How to bring a process to the front (make it the active window) through Runtime command line using its PID?
EDIT:
Is there a way to switch to an application window from command prompt using the PID of the application?
To switch to an application window from command prompt you can use Windows Script Host's AppActivate function. It accepts either ProcessID or window's title as its argument. Here is a simple script:
set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate Wscript.Arguments(0)
Then call the script by using cscript AppActivate.vbs 1234
I tried to apply the advice above into a complete solution
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static org.apache.commons.lang3.math.NumberUtils.toInt;
public class WindowSwither {
private static final Pattern TASKLIST_CSV_PATTERN = Pattern.compile("\".*?\",\"(\\d+)\".*");
private int pidActive = 0;
private final List<Integer> pidList = new ArrayList<>();
public WindowSwither(String exeName) throws IOException {
Process p = Runtime.getRuntime().exec("tasklist /FI \"ImageName eq " + exeName + ".exe\" /FO CSV");
for (String line : showProcessOut(p)) {
Matcher m = TASKLIST_CSV_PATTERN.matcher(line);
if (m.find()) {
pidList.add(toInt(m.group(1)));
}
}
}
public void next() throws IOException {
if (pidList.size() == 0) {
System.out.println("List empty! Ignored.");
return;
}
if (pidActive == 0) {
pidActive = pidList.get(0);
System.out.println("[0] " + pidActive);
} else {
Iterator<Integer> it = pidList.iterator();
while (it.hasNext()) {
Integer pid = it.next();
if (pid == pidActive) {
break;
}
}
if (it.hasNext()) {
pidActive = it.next();
System.out.println("[+] " + pidActive);
} else {
pidActive = pidList.get(0);
System.out.println("[0] " + pidActive);
}
}
activate(pidActive);
}
private static void activate(int pid) throws IOException {
String pathname = System.getProperty("java.io.tmpdir") + "WindowSwintcherAppActivate.vbs";
File file = new File(pathname);
if (!file.exists()) {
String content = "set WshShell = CreateObject(\"WScript.Shell\")\n" +
"WshShell.AppActivate Wscript.Arguments(0)";
writeStringToFile(file, content, StandardCharsets.UTF_8);
}
Runtime.getRuntime().exec("cscript " + pathname + " " + pid);
}
private List<String> showProcessOut(Process p) throws IOException {
List<String> list = new ArrayList<>();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "cp866"));
String line;
while ((line = in.readLine()) != null) {
list.add(line);
}
return list;
}
}
Main class
public class EnumerateWindows {
public static void main(String[] args) throws IOException, InterruptedException {
WindowSwither swither = new WindowSwither("notepad");
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
}
}

Problems in Database Management - sqlite with Java (IDE: NetBeans)

I have some problems in managing the storage of data via query (NetBeans-> Java-> Sqlite):
1) I have a folder with some txt file, containing several lines of text (the files do not exceed 2 Kb)
2) The program opens the files in sequence, and stores each word in a table
3)When the program comes to analyze too much data (some time more than 40 files ore more then 82) returns the following error
Exception in thread "main" java.sql.SQLException: unable to open database file
at org.sqlite.DB.throwex (DB.java: 288)
at org.sqlite.DB.executeBatch (DB.java: 236)
at org.sqlite.PrepStmt.executeBatch (PrepStmt.java: 83)
The error is in int [] upCountsb = prepb.executeBatch();
Here the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, InterruptedException {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:/Users/.../test.db");
Statement stmt;
stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS words");
stmt.executeUpdate("CREATE TABLE words (words)");
String path_dir ="C:/Users/.../good";
File currentDIR = new File("C:/Users/.../good");
File files[]=currentDIR.listFiles();
String tmp="";
ArrayList app = new ArrayList();
//Search in DIR for Files
for( File f1 : files ){
String nameFile = f1.getName();
FileReader f = null;
BufferedReader fIN = null;
String s;
//Open the file xxx.txt
try{
f = new FileReader(path_dir+"/"+nameFile);
fIN = new BufferedReader(f);
s = fIN.readLine();
while(s != null) {
StringTokenizer st = new StringTokenizer(s);
while(st.hasMoreTokens()) {
String str = st.nextToken().toString().toLowerCase();
Pattern pattern =Pattern.compile("\\W", Pattern.MULTILINE);
String newAll = pattern.matcher(str).replaceAll("").trim();
tmp=newAll;
app.add(tmp); //Add all data in the ArrayList app
} // Close While 'hasMoreTokens'
s = fIN.readLine();
} //Close While on File
} //Close TRAY
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
f.close(); //Close FileReader
} //Close Scan DIR for FILE
//Add all data in the Tbl od Database
PreparedStatement prep = conn.prepareStatement("insert into words values (?);");
for (int z=0; z<app.size();z++){
prep.setString(1,app.get(z).toString().toLowerCase());
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch(); ***//Here I get the error although i use int [] Count =prep.executeBatch();***
conn.setAutoCommit(true);
}
prep.close();
} //Close MAIN
You need to release the resources you are using once you are done with them. E.g. prepb.close() after executing the statement.
The same thing goes for your file handles.
Also, the point of batching is lost if you execute the statement for every insert.
Since your files are very small you might as well prepare all the data in memory before you persist it to a database.
package stackoverflow.wordanalysis;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
public class WordFrequencyImporter {
public static void main(String[] args) throws Exception {
List<String> words = readWords("the-directory-from-which-to-read-the-files");
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
try {
createWordsTable(conn);
persistWords(words, conn);
} finally {
conn.close();
}
}
private static void persistWords(List<String> words, Connection conn)
throws SQLException {
System.out.println("Persisting " + words.size() + " words");
PreparedStatement prep = conn
.prepareStatement("insert into words values (?);");
try {
for (String word : words) {
prep.setString(1, word);
prep.addBatch();
}
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
} finally {
prep.close();
}
}
private static void createWordsTable(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate("DROP TABLE IF EXISTS words");
stmt.executeUpdate("CREATE TABLE words (words)");
} finally {
stmt.close();
}
}
private static List<String> readWords(String path_dir) throws IOException {
Pattern pattern = Pattern.compile("\\W", Pattern.MULTILINE);
List<String> words = new ArrayList<String>();
for (File file : new File(path_dir).listFiles()) {
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println("Reading " + file);
try {
String s;
while ((s = reader.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
String token = st.nextToken().toString().toLowerCase();
String word = pattern.matcher(token).replaceAll("")
.trim();
words.add(word);
}
}
} finally {
reader.close();
}
}
return words;
}
}

Categories