I cannot seem to figure this out. In the method below I'm trying to write a boolean to a file in 2 places, however nothing is actually being written. Any help would be greatly appreciated.
private void renameTables(){
String path = MessengerMain.getInstance().getDataFolder() + File.separator + "v3-0-0 Table Rename.txt";
File f = new File(path);
try(ResultSet rs = conn.getMetaData().getTables(null, null, "%", null); Writer w = new PrintWriter(new FileOutputStream(f, false))){
if (!f.exists()){
f.createNewFile();
w.write("false");
w.flush();
}
List<String> lines = Files.readAllLines(Paths.get(path));
if (lines.get(0).equalsIgnoreCase("false")){
System.out.println("[Messenger] Verifying table names...");
int count = 0;
List<String> tables = new ArrayList<String>();
tables.add("messages");
tables.add("scores");
tables.add("contacts");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
if (tables.contains(table)){
update("ALTER TABLE " + table + " RENAME TO " + ("messenger_" + table) + ";");
count++;
}
}
if (count > 0){
System.out.println("[Messenger] Done. " + count + " table" + (count == 1 ? "" : "s") + " renamed.");
}else{
System.out.println("[Messenger] Done. No tables need to be renamed.");
}
w.write("true");
w.flush();
}
} catch (SQLException | IOException e){
e.printStackTrace();
}
}
Following Elliot Frisch's advice (same results):
private void renameTables(){
String path = MessengerMain.getInstance().getDataFolder() + File.separator + "v3-0-0 Table Rename.txt";
File f = new File(path);
try(ResultSet rs = conn.getMetaData().getTables(null, null, "%", null)){
Writer w = new PrintWriter(new FileOutputStream(f, false));
if (!f.exists()){
f.createNewFile();
w.write("false");
w.close(); //close here
}
List<String> lines = Files.readAllLines(Paths.get(path));
if (lines.get(0).equalsIgnoreCase("false")){
System.out.println("[Messenger] Verifying table names...");
int count = 0;
List<String> tables = new ArrayList<String>();
tables.add("messages");
tables.add("scores");
tables.add("contacts");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
if (tables.contains(table)){
update("ALTER TABLE " + table + " RENAME TO " + ("messenger_" + table) + ";");
count++;
}
}
if (count > 0){
System.out.println("[Messenger] Done. " + count + " table" + (count == 1 ? "" : "s") + " renamed.");
}else{
System.out.println("[Messenger] Done. No tables need to be renamed.");
}
w = new PrintWriter(new FileOutputStream(f, false)); //create a new writer
w.write("true");
w.close(); //close here
}
} catch (SQLException | IOException e){
e.printStackTrace();
}
}
Here is a working full minimal, complete, verifiable example
public static void main(String[] args) {
File f = new File(System.getProperty("user.home"), "temp.txt");
String path = f.getPath();
try (Writer w = new FileWriter(f)) {
w.write("false");
} catch (IOException e) {
e.printStackTrace();
}
try {
List<String> lines = Files.readAllLines(Paths.get(path));
System.out.println(lines);
} catch (IOException e) {
e.printStackTrace();
}
}
Output is (as expected)
[false]
Related
When I open the view window, I enter the value of facultyCode and if I enter an existing value, then everything is fine, and if I enter a non-existent value, then the window freezes and nothing happens
CLIENT
#FXML
void initialize() {
showButton.setOnAction(actionEvent -> {
String input = null;
try {
socket = new Socket("127.0.0.1",3024);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String facultyCode = facultyCodeArea.getText();
String output = "SELECT * FROM Faculty WHERE facultyCode = " + facultyCode + ";";
try {
outputStream.writeUTF(output);
outputStream.flush();
input = inputStream.readUTF(); //if the input is incorrect, input is not assigned to
//anything
} catch (IOException e) {
e.printStackTrace();
}
String[] dataServer = input.split(" ");
String name = dataServer[0];
nameArea.setText(name);
String code = dataServer[1];
facultyCodeArea.setText(code);
String number = dataServer[2];
numberSubjectsArea.setText(number);
String main = dataServer[3];
mainSubjectArea.setText(main);
String dean = dataServer[4];
deanArea.setText(dean);
String language = dataServer[5];
languageStudyArea.setText(language);
});
}
SERVER
else if (isSelectQuery(input)) {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(input);
while (resultSet.next()) {
String name = resultSet.getString("name");
int codeFaculty = resultSet.getInt("facultyCode");
int numberSubject = resultSet.getInt("numberSubjects");
String mainSubject = resultSet.getString("mainSubject");
String dean = resultSet.getString("dean");
String languageStudy = resultSet.getString("languageStudy");
String output = name + " " +
codeFaculty + " " +
numberSubject + " " +
mainSubject + " " +
dean + " " +
languageStudy;
outputStream.writeUTF(output);
outputStream.flush();
}
}
I've tried closing the window if an exception occurs, I've also tried closing the window if input = null, but didn't help
SERVER
String output = "error";
else if (isSelectQuery(input)) {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(input);
while (resultSet.next()) {
String name = resultSet.getString("name");
int codeFaculty = resultSet.getInt("facultyCode");
int numberSubject = resultSet.getInt("numberSubjects");
String mainSubject = resultSet.getString("mainSubject");
String dean = resultSet.getString("dean");
String languageStudy = resultSet.getString("languageStudy");
output = name + " " +
codeFaculty + " " +
numberSubject + " " +
mainSubject + " " +
dean + " " +
languageStudy;
}
outputStream.writeUTF(output);
outputStream.flush();
}
CLIENT
#FXML
void initialize() {
showButton.setOnAction(actionEvent -> {
String input = null;
try {
socket = new Socket("127.0.0.1",3024);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String facultyCode = facultyCodeArea.getText();
String output = "SELECT * FROM Faculty WHERE facultyCode = " + facultyCode + ";";
try {
outputStream.writeUTF(output);
outputStream.flush();
input = inputStream.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String[] dataServer = input.split(" ");
if(!dataServer[0].equals("error")) {
String name = dataServer[0];
nameArea.setText(name);
String code = dataServer[1];
facultyCodeArea.setText(code);
String number = dataServer[2];
numberSubjectsArea.setText(number);
String main = dataServer[3];
mainSubjectArea.setText(main);
String dean = dataServer[4];
deanArea.setText(dean);
String language = dataServer[5];
languageStudyArea.setText(language);
}
else {
errorArea.setText("Not exist");
}
});
}
So I first assign output = error and if the request does not return anything, then I send it to the client, if on request something came, I assign values and send it to the client. Next, I process the data on the client
I have two models in my program, Bus and Learner.
Each is stored in a txt file, name Busses.txt and Learners.txt, respectively.
I am experiencing an issue where the method to delete a learner entry works, but the method to delete a bus entry does not, even though the code is practically identical.
Learner delete method:
public void deleteLearner(String ID) {
removeBlankLines("Learners.txt");
File oldFile = new File("Learners.txt");
File tempFile = new File("tempFile.txt");
String removeKey = ID;
String LearnerID;
String nameSurname;
boolean status;
String busOfLearner;
String line;
String lineToKeep;
try {
Scanner scFile = new Scanner(new File("Learners.txt"));
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line).useDelimiter("#");
LearnerID = scLine.next();
nameSurname = scLine.next();
status = scLine.nextBoolean();
if (scLine.hasNext()) {
busOfLearner = scLine.next();
} else {
busOfLearner = "";
}
if (!LearnerID.equalsIgnoreCase(removeKey)) {
lineToKeep = LearnerID + "#" + nameSurname + "#" + status + "#" + busOfLearner + "\n";
FileWriter fWriter = new FileWriter(tempFile,true);
BufferedWriter bWriter = new BufferedWriter(fWriter);
bWriter.write(lineToKeep);
bWriter.close();
fWriter.close();
}
scLine.close();
}
scFile.close();
boolean successfulDelete = oldFile.delete();
File transfer = new File("Learners.txt");
boolean successfulRename = tempFile.renameTo(transfer);
}
catch (Exception e) {
System.out.println("An error has occured deleting a learner record " + e);
}
}
Delete bus method:
public void deleteBus(String removeBusName) {
removeBlankLinesBus("Busses.txt");
File oldFile = new File("Busses.txt");
File newFile = new File("NewBusFile.txt");
String deleteKey = removeBusName;
String currentBusName;
int currentNumSeats;
String currentPickLocation;
String currentDropLocation;
String currentPickTime;
String currentDropTime;
String line;
String lineToKeep;
try {
Scanner scFile = new Scanner(new File("Busses.txt"));
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line).useDelimiter("#");
currentBusName = scLine.next();
currentNumSeats = scLine.nextInt();
currentPickLocation = scLine.next();
currentDropLocation = scLine.next();
currentPickTime = scLine.next();
currentDropTime = scLine.next();
if (!currentBusName.equalsIgnoreCase(deleteKey)) {
lineToKeep = currentBusName + "#" + currentNumSeats + "#" + currentPickLocation + "#" + currentDropLocation + "#" + currentPickTime + "#" + currentDropTime + "\n";
FileWriter fWriter = new FileWriter(newFile,true);
BufferedWriter bWriter = new BufferedWriter(fWriter);
bWriter.write(lineToKeep);
bWriter.close();
fWriter.close();
}
scLine.close();
}
scFile.close();
boolean successfulDelete = oldFile.delete();
File transfer = new File("Busses.txt");
boolean successfulRename = newFile.renameTo(transfer);
}
catch (Exception e) {
System.out.println("An error has occured deleting " + removeBusName + " from the file: " + e);
}
}
Problem:
With the delete bus method, the old file doesn't get deleted and the temporary or new file doesn't get renamed to the original file.
I am very confident that all files, streams, scanners, etc. are closed, as it is exactly the same as I did in the delete learner method, which does work and the files are deleted and renamed in the learner delete method as it should.
Assistance would be greatly appreciated.
EDIT: Implementation of methods:
Learner:
System.out.println(myController.PrintLearnerArr(myController.LoadLearner("Learners.txt")));
String delete = "0210045112055";
myController.deleteLearner(delete);
System.out.println(myController.PrintLearnerArr(myController.LoadLearner("Learners.txt")));
Bus:
System.out.println(myController.PrintBusArr(myController.LoadBus("Busses.txt")));
String deleteKey = "deleteme";
myController.deleteBus(deleteKey);
System.out.println(myController.PrintBusArr(myController.LoadBus("Busses.txt")));
I wrote a big chunk of codes that downloads CSV file from url, then i bulk inserted into sql database, then call data from SQL server and display on Java console. Finally select the column I want to keep and export as a new CSV file.
but all of those codes are in the same class right now. How can I separate them into different class like I want a class for just download file and another class just do the Bulk insert and another class to just do the Select Query.
Thanks for helping me out
below is my code in one class now
public class ProjectTest extends CreateTable {
public static void main(String[] args) throws MalformedURLException {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
URL url = new URL(
"https://quality.data.gov.tw/dq_download_csv.php?nid=43983&md5_url=9d38afbca8243a24b5b89d03a8070aff");
try (InputStream inputStream = url.openStream();
FileOutputStream fos = new FileOutputStream(
"C:\\Users\\ALICE\\Desktop\\Java\\Dropbox\\Java\\virus.csv");
Connection connection = DriverManager
.getConnection("jdbc:sqlserver://localhost:1433;databaseName=JDBCDB", "andy3", "andy"); // andy3
// //
// ,andy
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
FileOutputStream fos2 = new FileOutputStream(
"C:\\Users\\ALICE\\Desktop\\Java\\Dropbox\\Java\\NEWvirus.csv");
OutputStreamWriter osw = new OutputStreamWriter(fos2, "MS950");
BufferedWriter bw = new BufferedWriter(osw);
) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
stmt.executeUpdate("DROP TABLE Virus");
boolean rs = stmt.execute(CreateTable);
System.out.println("Database Created");
PreparedStatement pstmt = connection.prepareStatement(InsertData);
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Data Inserted");
} else {
System.out.println("Insert ERROR");
}
ResultSet rs4 = stmt.executeQuery("SELECT Count(*) FROM Virus");
int numberOfData = rs4.getInt(1);
System.out.println(numberOfData);
ResultSet rs3 = stmt.executeQuery(selectQuery);
ResultSetMetaData metaData = rs3.getMetaData();
DatabaseMetaData DmetaData = connection.getMetaData();
String[] types = { "TABLE" };
ResultSet rs5 = DmetaData.getTables(null, null, "Virus", types);
List<String> ColNameList = new ArrayList<String>();
while (rs5.next()) {
String tableName = rs5.getString("TABLE_NAME");
ResultSet columnRs = DmetaData.getColumns(null, null, tableName, null);
while (columnRs.next()) {
String columnName = columnRs.getString("COLUMN_NAME");
ColNameList.add(columnName);
}
System.out.print("|" + ColNameList.get(0) + " |");
System.out.print(ColNameList.get(1) + " |");
System.out.print(ColNameList.get(2) + "|");
System.out.print(ColNameList.get(3) + "|");
System.out.print(ColNameList.get(4) + " |");
System.out.print(ColNameList.get(5) + " |");
System.out.print(ColNameList.get(6) + " |");
System.out.print(ColNameList.get(7) + " |");
System.out.print(ColNameList.get(8) + "|");
System.out.print(ColNameList.get(9) + " |");
System.out.print(ColNameList.get(10) + " |");
System.out.print(ColNameList.get(11) + "|");
System.out.print(ColNameList.get(12) + " |");
System.out.print(ColNameList.get(13) + " |");
System.out.print(ColNameList.get(14) + " |");
System.out.print(ColNameList.get(15) + "");
}
System.out.println();
while (rs3.next()) {
coList1.add(rs3.getString(1));
coList2.add(rs3.getString(2));
coList3.add(rs3.getString(3));
coList4.add(rs3.getString(4));
coList5.add(rs3.getString(5));
coList6.add(rs3.getString(6));
coList7.add(rs3.getString(7));
coList8.add(rs3.getString(8));
coList9.add(rs3.getString(9));
coList10.add(rs3.getString(10));
coList11.add(rs3.getString(11));
coList12.add(rs3.getString(12));
coList13.add(rs3.getString(13));
coList14.add(rs3.getString(14));
coList15.add(rs3.getString(15));
coList16.add(rs3.getString(16));
coList17.add(rs3.getString(17));
}
for (int p = 0; p < 20; p++) { // coList9.size(
System.out.print("|" + coList1.get(p) + "|");
String str2 = coList2.get(p);
if (str2.length() < 3) {
String blank = " ";
String repeated = new String(new char[(3 - str2.length())]).replace("\0", blank);
System.out.print(repeated + coList2.get(p) + "|");
} else {
System.out.print(coList2.get(p) + "|");
}
System.out.print(" " + coList3.get(p) + "|");
System.out.print(coList4.get(p) + "|");
System.out.print(coList5.get(p) + "|");
System.out.print(coList6.get(p) + "|");
System.out.print(coList7.get(p) + "|");
System.out.print(coList8.get(p) + "|");
String str = coList9.get(p);
if (str.length() < 5) {
String blank = " ";
String repeated = new String(new char[(5 - str.length())]).replace("\0", blank);
System.out.print(repeated + coList9.get(p) + "|");
} else {
System.out.print(coList9.get(p) + "|");
}
System.out.print(coList10.get(p) + "|");
System.out.print(coList11.get(p) + "|");
String str12 = coList12.get(p);
if (str12.length() < 5) {
String blank = " ";
String repeated = new String(new char[(6 - str12.length())]).replace("\0", blank);
System.out.print(repeated + coList12.get(p) + "|");
} else {
System.out.print(coList12.get(p) + "|");
}
String str13 = coList13.get(p);
if (str13.length() < 5) {
String blank = " ";
String repeated = new String(new char[(4 - str13.length())]).replace("\0", blank);
System.out.print(repeated + coList13.get(p) + "|");
} else {
System.out.print(coList12.get(p) + "|");
}
System.out.print(coList14.get(p) + "|");
System.out.print(coList15.get(p) + "|");
System.out.print(coList16.get(p) + "|");
System.out.print(coList17.get(p) + "|");
System.out.println();
}
rs3.beforeFirst();
StringBuilder builder = new StringBuilder();
builder.append("CaseID").append(",").append("Age").append(",").append("Gender").append(",").append("City")
.append(",").append("SampleDate").append(",").append("VirusType").append(",")
.append("SubType").append(",").append("Locus").append(",").append("Primer").append(",").append("GeneDirection")
.append(",").append("TypingMethod").append(",").append("DNASeq").append(",").append("AminoAcidSeq");
System.out.println(rs3.next());
while (rs3.next()) {
builder.append(System.lineSeparator());
builder.append(rs3.getString(1)).append(",").append(rs3.getString(2)).append(",")
.append(rs3.getString(3)).append(",").append(rs3.getString(5)).append(",")
.append(rs3.getString(7)).append(",").append(rs3.getString(10)).append(",")
.append(rs3.getString(11)).append(",").append(rs3.getString(12)).append(",")
.append(rs3.getString(13)).append(",").append(rs3.getString(14)).append(",")
.append(rs3.getString(15)).append(",").append(rs3.getString(16)).append(",").append(rs3.getString(17)).append(",");
}
bw.write(builder.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
Start refactoring your code in small steps and then iteratively improve your design if needed.
As you have mentioned the algorithmic approach, leveraging that this should be your starting step.
CSV file from url,
then i bulk inserted into sql database,
then call data from SQL server and
display on Java console.
Finally select the column I want to keep
and export as a new CSV file.
Small helper functions for each of these steps.
Read more about SOLID design principles if that helps in improving your solution.
The background info here is that I have a working Indexer and Search (in java) that indexes and searches a file directory for the filenames and then copies the files to a "Results" Directory.
What I need/ don't have much experience in is writing jsp files. I need the jsp file to have a search bar for the text and then a search button. When text is entered in the bar, and the button is clicked, I need it to run my search program with the entered text as an arg.
I have added the IndexFiles and the SearchFiles classes for reference.
Please explain with a good example if you can help out!
public class SearchFiles {
static File searchDirectory = new File(
"C:\\Users\\flood.j.2\\Desktop\\IndexSearch\\Results");
static String v = new String();
static String path = null;
String title = null;
File addedFile = null;
OutputStream out = null;
String dirName = "C:\\Users\\flood.j.2\\Desktop\\IndexSearch\\Results";
public static void main(String[] args) throws Exception {
String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string]";
if (args.length > 0
&& ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.exit(0);
}
for (int j = 5; j < args.length; j++) {
v += args[j] + " ";
}
String index = "index";
String field = "contents";
String queries = null;
boolean raw = false;
String queryString = null;
int hits = 100;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
index = args[i + 1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i + 1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i + 1];
i++;
} else if ("-query".equals(args[i])) {
queryString = v;
i++;
}
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
index)));
IndexSearcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(
queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
}
QueryParser parser = new QueryParser(Version.LUCENE_40, field, analyzer);
for (int m = 0; m < 2; m++) {
if (queries == null && queryString == null) {
System.out.println("Enter query: ");
}
String line = queryString != null ? queryString : in.readLine();
if (line == null || line.length() == -1) {
break;
}
line = line.trim();
if (line.length() == 0) {
break;
}
Query query = parser.parse(line);
System.out.println("Searching for: " + query.toString(field));
doPagingSearch(in, searcher, query, hits, raw, queries == null
&& queryString == null);
if (queryString == null) {
break;
}
}
reader.close();
}
public static void doPagingSearch(BufferedReader in,
IndexSearcher searcher, Query query, int hitsPerPage, boolean raw,
boolean interactive) throws IOException {
// Collect enough docs to show 500 pages
TopDocs results = searcher.search(query, 5 * hitsPerPage);
ScoreDoc[] hits = results.scoreDocs;
int numTotalHits = results.totalHits;
System.out.println(numTotalHits + " total matching documents");
int start = 0;
int end = Math.min(numTotalHits, hitsPerPage);
FileUtils.deleteDirectory(searchDirectory);
while (true) {
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
path = doc.get("path");
if (path != null) {
System.out.println((i + 1) + ". " + path);
File addFile = new File(path);
try {
FileUtils.copyFileToDirectory(addFile, searchDirectory);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (!interactive || end == 0) {
break;
}
System.exit(0);
}
}
}
public class IndexFiles {
private IndexFiles() {
}
public static void main(String[] args) {
String usage = "java org.apache.lucene.demo.IndexFiles"
+ " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
+ "This indexes the documents in DOCS_PATH, creating a Lucene index"
+ "in INDEX_PATH that can be searched with SearchFiles";
String indexPath = null;
String docsPath = null;
boolean create = true;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
indexPath = args[i + 1];
i++;
} else if ("-docs".equals(args[i])) {
docsPath = args[i + 1];
i++;
} else if ("-update".equals(args[i])) {
create = false;
}
}
if (docsPath == null) {
System.err.println("Usage: " + usage);
System.exit(1);
}
final File docDir = new File(docsPath);
if (!docDir.exists() || !docDir.canRead()) {
System.out
.println("Document directory '"
+ docDir.getAbsolutePath()
+ "' does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
try {
System.out.println("Indexing to directory '" + indexPath + "'...");
Directory dir = FSDirectory.open(new File(indexPath));
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,
analyzer);
if (create) {
iwc.setOpenMode(OpenMode.CREATE);
} else {
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
}
IndexWriter writer = new IndexWriter(dir, iwc);
indexDocs(writer, docDir);
writer.close();
Date end = new Date();
System.out.println(end.getTime() - start.getTime()
+ " total milliseconds");
} catch (IOException e) {
System.out.println(" caught a " + e.getClass()
+ "\n with message: " + e.getMessage());
}
}
static void indexDocs(IndexWriter writer, File file) throws IOException {
if (file.canRead()) {
if (file.isDirectory()) {
String[] files = file.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
indexDocs(writer, new File(file, files[i]));
}
}
} else {
FileInputStream fis;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException fnfe) {
return;
}
try {
Document doc = new Document();
Field pathField = new StringField("path",
file.getAbsolutePath(), Field.Store.YES);
doc.add(pathField);
doc.add(new LongField("modified", file.lastModified(),
Field.Store.NO));
doc.add(new TextField("title", file.getName(), null));
System.out.println(pathField);
if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
System.out.println("adding " + file);
writer.addDocument(doc);
} else {
System.out.println("updating " + file);
writer.updateDocument(new Term("path", file.getPath()),
doc);
}
} finally {
fis.close();
}
}
}
}
}
First, you should definitely do this in a servlet rather than a JSP. Putting lots of logic in JSP is bad practice. (See the servlets info page).
Second, it would probably be better on performance to make a cronjob (Linux) or Task (Windows) to run the search program every hour and store the results in a database and just have your servlet pull from there rather than allow the user to initiate the search program.
I am making a program where I read data from .txt files and store them in tables. In my program the user would give the directory of the files, the program would find all the .txt files and for each one of these would create a table which would have as name the name of the file and each table would have two fields (text and price).
These two columns are separeted by space. In my code below is shown all the program. But I have problem when I am trying to import the data programmatically. The Error exception that I get is that I have error in SQL syntax. Could anyone help me because I am trying to solve it for a couple af days with no result?
public class notepad {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3330/mydb", "root", "root");
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
if (fl.canRead())
break;
System.out.println("Error:Directory does not exists");
}
try {
String files;
File folder = new File(dirpath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
List<File> txtFiles = new ArrayList<File>();
txtFiles.add(listOfFiles[i]);
String[] parts = files.split("\\.");
String tablename = parts[0];
for (File txtFile : txtFiles) {
List sheetData = new ArrayList();
try {
FileReader in = new FileReader(txtFile);
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
String filename = dirpath.substring(dirpath
.indexOf('\\') - 2, files
.indexOf(parts[0]));
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
getCreateTable1(con, tablename);
importData(con, txtFile, tablename);
}
}
}
}
} catch (Exception e) {
System.out.println();
}
}
private static String getCreateTable1(Connection con, String tablename) {
try {
Class.forName("com.mysql.jdbc.Driver");
Statement stmt = con.createStatement();
String createtable = "CREATE TABLE " + tablename
+ " ( text VARCHAR(255), price int )";
System.out.println("Create a new table in the database");
stmt.executeUpdate(createtable);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
private static String importData(Connection con, File txtFile,
String tablename) {
try {
Statement stmt;
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String importingdata = "LOAD DATA INFILE '"
+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename
+ " (text,price)";
stmt.executeUpdate(importingdata);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}
Try change
+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename
^
to
+ txtFile.getAbsolutePath() + "' INTO TABLE " + tablename
This orphan quote makes your statement invalid.