Java: Please insert "}" to complete classbody - java

I wrote a little test program but I'm experiencing a syntax error in my closing tags...
Here's the code
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
The compiler gives an error at the LATEST closing accolade:
"Please insert } to complete classbody"
And also at the last accolade of the "openFile()" method...
Any suggestions?

f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
//...
}
This whole block of logic is not in a method. It needs to be in a method or constructor.

Where you have
f = new File ...
...
catch ( .. )
{
....
}
You want to wrap that in
public static void main (String args[]) {
....
}
You cannot have a code block in a class definition. At the very top of the class, those variable declarations are declarations of class members with default visibility.

All the code starting with the line
f = new File(openFile());
is outside of any method. This is not legal Java: statements must be enclosed in a block or method body.

everything below
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
is not enclosed within a method body but is rather lurking in the class body. remove the outer closing brace above.

Your code is not in a method. It needs to be in a method or a static block. Guessing your intent you can put it in the constructor like :
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
}

Related

Why doesn't the file get deleted and renamed?

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")));

How to get the path of a file but without the actual file name

For example C:\Desktop and not C:\Desktop\file.txt.
Here's the code, what can i do to get only the path excluding the actual name of the file or do i have to mechanically remove the name part(String) with the split("\") method.
import java.io.*;
public class FilesInfo {
File file = new File("C:\\Users\\CCKS\\Desktop\\1");
public void viewFiles() throws IOException {
File[] files = file.listFiles();
String path = "";
for(int i = 0; i < files.length; i++){
if(!files[i].isDirectory()){
System.out.println("[DIRECTORY]" + files[i].getPath() + " [NAME] " + files[i].toString() + " [SIZE] " + files[i].length() + "KB");
} else {
path = files[i].getAbsolutePath();
file = new File(path);
}
}
if(path.equals("")){
return;
} else {
viewFiles();
}
}
public static void main(String [] args){
try {
new FilesInfo().viewFiles();
} catch (Exception e){
e.printStackTrace();
}
}
}
Like this,
File file = new File("C:\Desktop\file.txt");
String parentPath= file.getParent();
File file = new File( "C:/testDir/test1.txt" );
String justPath = file.getParent();

Creating a jsp search form to run a java Search program

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.

Java Gui Text files Output

try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}

Tokenizer not separating string? (JAVA)

I have a class Called File
Location which stores the size, name, drive and directory of a file.
The class is supposed to separate the extension from the file name ("java" from "test.java") then compare it to another file using an equals method. Though for some reason it is returning false everytime. Any idea what's wrong?
Class file
import java.util.*;
public class FileLocation
{
private String name;
private char drive;
private String directory;
private int size;
public FileLocation()
{
drive = 'X';
directory = "OOProgramming\\Practicals\\";
name = "test";
size = 2;
}
public FileLocation(char driveIn, String dirIn, String nameIn, int sizeIn)
{
drive = driveIn;
directory = dirIn;
name = nameIn;
size = sizeIn;
}
public String getFullPath()
{
return drive + ":\\" + directory + name;
}
public String getFileType()
{
StringTokenizer st1 = new StringTokenizer(name, ".");
return "File type is " + st1.nextToken();
}
public String getSizeAsString()
{
StringBuilder data = new StringBuilder();
if(size > 1048575)
{
data.append("gb");
}
else if(size > 1024)
{
data.append("mb");
}
else
{
data.append("kb");
}
return size + " " + data;
}
public boolean isTextFile()
{
StringTokenizer st2 = new StringTokenizer(name, ".");
if(st2.nextToken() == ".txt" || st2.nextToken() == ".doc")
{
return true;
}
else
{
return false;
}
}
public void appendDrive()
{
StringBuilder st1 = new StringBuilder(drive);
StringBuilder st2 = new StringBuilder(directory);
StringBuilder combineSb = st1.append(st2);
}
public int countDirectories()
{
StringTokenizer stDir =new StringTokenizer(directory, "//");
return stDir.countTokens();
}
public String toString()
{
return "Drive: " + drive + " Directory: " + directory + " Name: " + name + " Size: " + size;
}
public boolean equals(FileLocation f)
{
return drive == f.drive && directory == f.directory && name == f.name && size == f.size;
}
}
Tester program
import java.util.*;
public class FileLocationTest
{
public static void main(String [] args)
{
Scanner keyboardIn = new Scanner(System.in);
FileLocation javaAssign = new FileLocation('X', "Programming\\Assignment\\", "Loan.txt", 1);
int selector = 0;
System.out.print(javaAssign.isTextFile());
}
}
this code will give true only if the file is doc.
StringTokenizer st2 = new StringTokenizer(name, ".");
if(st2.nextToken() == ".txt" || st2.nextToken() == ".doc")
if file name file.txt then what happend
(st2.nextToken() == ".txt") means ("file" == "txt") false
(st2.nextToken() == ".doc") means ("txt" == "txt") false
first token will gave file name second token will gave ext.
right code is
StringTokenizer st2 = new StringTokenizer(name, ".");
String filename = st2.nextToken();
String ext = st2.nextToken();
if(ext.equalsIgnoreCase(".txt") || ext.equalsIgnoreCase(".txt"))
use always equals to compare strings not ==
Take a look at my own question I posted a while back. I ended up using Apache Lucene's tokenizer.
Here is how you use it (copied from here):
TokenStream tokenStream = analyzer.tokenStream(fieldName, reader);
OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);
CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
while (tokenStream.incrementToken()) {
int startOffset = offsetAttribute.startOffset();
int endOffset = offsetAttribute.endOffset();
String term = charTermAttribute.toString();
}

Categories