Display searched text with line numbers in a text file - java

So I've been working on a program that will display the line number and the line itself of the searched text string. If I search dog, and I have lines in my text file that contain the word dog, those lines and line numbers should be shown. I also have created a method that counts the characters, words, and lines of a text file. However, the problem I am having is that whenever I run my program I don't get the line numbers with the lines of the searched text. I successfully get the text from the text file in the console and I successfully get the number of lines, words, etc.
Here's my written code, I am guessing it has to do something with the fact that I don't have a "return results;" statement, but I am not sure where to put it, and if I add it to the end of "+ characters + " characters. "" line by doing "+ results", it just gives me empty brackets.
Maybe I am doing something wrong? Perhaps something to do with closing the file and stream, not sure. Please help, I've tried moving stuff around but no luck.
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
Here's the main class if needed:
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class BasicFile {
File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");
public BasicFile() {
selection = new JFileChooser(".");
}
public void selectFile() {
int status = selection.showOpenDialog(null);
try {
if (status != JFileChooser.APPROVE_OPTION) {
throw new IOException();
}
file1 = selection.getSelectedFile();
if (!file1.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.exit(0);
}
}
public void backupFile() throws FileNotFoundException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new FileInputStream(file1));
out = new DataOutputStream(new FileOutputStream(file2));
try {
while (true) {
byte data = in.readByte();
out.writeByte(data);
}
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "File has been backed up!",
"Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found ",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
display(e.toString(), "Error");
}
}
}
boolean exists() {
return file1.exists();
}
public String toString() {
return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
void display(String msg, String s) {
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}
}

You are nearly there.
reinitialize your FileReader and LineNumberReader before your while ((line = lnr.readLine()) != null) loop.
Then your ArrayList will be full of the #String that I think you desire.

what you can do is start counting the lines in the file (starting by 0), then increase by 1 every time a new line is found.. then check if the string you want to find is contained in the line, then print the number of the line where the keyword is found (using the contains() function in Java). I assumed you want to check for both upper and lower case, if you don't want that then simply remove the toLowerCase() ! So, read the file properly in Java:
long lineNumber = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
lineNumber++;
System.out.println("The line I am now examining is : " + line + " and the line number is : " + lineNumber);
if line.toLowerCase().contains(word.toLowerCase()) {
System.out.println("Line number: " + lineNumber + " contains keyword : " + word);
line = myReader.readLine();
}

Related

Issues with readLine

Just try to get the line right in the while statement
try {
FileReader fr = new FileReader("Original.txt");
BufferedReader br = new BufferedReader(fr);
String strFullName;
while ((strFullName = br.readLine()) != null) {
int intSpaceLocation = strFullName.indexOf(" ");
String strLastName = strFullName.substring(0, intSpaceLocation);
String strFirstName = strFullName.substring(intSpaceLocation + 1);
System.out.println("First Name = " + strFirstName + " Last Name = " + strLastName);
}
br.close();
fr.close();
} catch (Exception e) {
}
I am trying to get each line from a file and trying to split it with a space, but it only does it for the first line
Output:
First Name = Todd Last Name = Jackson

Parsing strings with split JAVA

I'm trying to find an object in a list from a text file
Example:
L;10;€10,50;83259875;YellowPaint
-H;U;30;€12,00;98123742;Hammer
G;U;80;€15,00;87589302;Seeds
By inserting 98123742 by input with scanner, i want to find that string.
I tried to do this:
private static void inputCode() throws IOException {
String code;
String line = null;
boolean retVal = false;
System.out.println("\ninsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if (token[0].equals(code) && token[1].equals(code)) {
retVal = true;
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("impossible open the file " + fileName);
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
System.out.println(retVal);
}
How can i print "-H;U;30;€12,00;98123742;Hammer" inserting "98123742" (that is the code of the product) ?
Why are you splitting in the first place? For such a simple usecase, and with that line format, I'd go with
line.contains(";" + code);
Not much else to do.

Debugging File Search / Merge Code

This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}

Searching a FIle: Beginner Code

I am in college for programming and we were given an assignment to create a program that allows the user to open a file from their computer and obtain information from that file that is selected. One part of my assignment states the following:
Search the file line by line for a given string. The output must contain the line number, followed by the contents of the line that contains the search argument. For instance given the following the search string: Java, the program would search the file line by line generating a result such as the following:
5: on the island of Java
9: The people of JAVA loves jaVa.
Use the class LineNumberReader for this exercise.
I have my code below, and I am not sure what I am doing wrong. There is no syntax error, just seems to be a logic error. When I run the code I am able to get the file description, backup the file, get the word count, and exit properly, but when asked to search for a word as described above I am not getting the output that I am supposed to get, it only gives me the word count and no search results.
Main Class
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class BasicFile {
File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");
public BasicFile() {
selection = new JFileChooser(".");
}
public void selectFile() {
int status = selection.showOpenDialog(null);
try {
if (status != JFileChooser.APPROVE_OPTION) {
throw new IOException();
}
file1 = selection.getSelectedFile();
if (!file1.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.exit(0);
}
}
void backupFile() throws FileNotFoundException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new FileInputStream(file1));
out = new DataOutputStream(new FileOutputStream(file2));
try {
while (true) {
byte data = in.readByte();
out.writeByte(data);
}
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "Success!!!",
"Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found ",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
display(e.toString(), "Error");
}
}
}
boolean exists() {
return file1.exists();
}
public String toString() {
return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
BufferedReader bf = new BufferedReader(new FileReader(file1));
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("output.txt"));
int recCount = 0;
String record = null;
while ((record = bf.readLine()) != null) {
recCount++;
out.write(recCount + ": " + record);
out.newLine();
}
out.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
void display(String msg, String s) {
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}
}
Test Class
import java.io.*;
import javax.swing.*;
public class TestBasicFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
boolean done = false;
String menu = "Enter option\n1. Open File\n2. Backup File\n3. "
+ "Word Count\n4. Exit";
while (!done) {
BasicFile f = new BasicFile();
String s = JOptionPane.showInputDialog(menu);
try {
int i = Integer.parseInt(s);
switch (i) {
case 1:
JOptionPane.showMessageDialog(null, "When the file is selected, the name, path, and size will be displayed",
"File Selection", JOptionPane.INFORMATION_MESSAGE);
f.selectFile();
if (f.exists()) {
displayInfo(f.toString(), "File");
} else {
f.selectFile();
}
break;
case 2:
f.selectFile();
if (f.exists()) {
displayInfo(f.toString(), "File");
} else {
f.selectFile();
}
f.backupFile();
break;
case 3:
f.selectFile();
if (f.exists()) {
displayInfo(f.words(), "Word Count");
} else {
f.selectFile();
}
break;
case 4:
done = true;
break;
default:
}
} catch (NumberFormatException e) {
System.exit(0);
} catch (NullPointerException e) {
System.exit(0);
}
}
}
static void displayInfo(String s, String info) {
JOptionPane.showMessageDialog(null, s, info, JOptionPane.INFORMATION_MESSAGE);
}
}
You put the results in the results list, but never print that.

File IO Exceptions in Java

I am reading input from a tab delimited file in a java class. The file opens properly and the information from the file seems to be read in correctly as well. Every line in the file winds up printing to the screen as expected but then at the end of file it seems like it tries to print one more line and I get an ArrayIndexOutOfBoundsException: 1.
It is worth noting that if I uncomment the line where I output the value of sCurrentline and comment out the output of the split array I do not get the error.
Code:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fname));
while ((sCurrentLine = br.readLine()) != null){
String[] values = sCurrentLine.split("\\t", -1); // don't truncate empty fields
System.out.println("Col1: " + values[0] + " Col2: " + values[1] + " Col3: "
+ values[2] + " Col4: " + values[3] + " Col5: " + values[4] );
//System.out.println(sCurrentLine);
}
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} finally {
try {
if(br != null){
br.close();
}
} catch (IOException ex) {
System.out.println("ErrorClosingFile");
ex.printStackTrace();
}
}
The last line has not the same amount of elements as the other lines. After splitting the last line, you try to access fields of the array, that do not exist. That is indicated by the exception http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html. Before you access the fields of the array, you have to check if there is the expected amount of items in it. Like this:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fname));
while ((sCurrentLine = br.readLine()) != null){
String[] values = sCurrentLine.split("\\t", -1); // don't truncate empty fields
if (5 == values.length) {
System.out.println("Col1: " + values[0] + " Col2: " + values[1] + " Col3: "
+ values[2] + " Col4: " + values[3] + " Col5: " + values[4] );
}
// System.out.println(sCurrentLine);
}
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} finally {
try {
if(br != null){
br.close();
}
} catch (IOException ex) {
System.out.println("ErrorClosingFile");
ex.printStackTrace();
}
}
the code seems ok... do you have an empty newline at the end?
while ((sCurrentLine = br.readLine()) != null){
if (sCurrentLine.isEmpty() || sCurrentLine.startsWith(";")) // skip empty and comment lines
continue;
String[] values = sCurrentLine.split("\\t"); // are you sure the -1 is required?
...
}
Try this
String[] values = "".split("\\t", -1); // don't truncate empty fields
int index=1;
StringBuffer sb = new StringBuffer();
for (String value : values) {
sb.append("Col"+index+":").append(value).append(" ");
index++;
}
System.out.println(sb.toString());
Is obvious that you are reading an array position that does not exist

Categories