Find words within a text file
Hey all.
I am playing around with the idea of finding a line of text within a text file, by using scanner and some next methods.
The way I am trying to get it to work is that one enters a string and the program then finds all the lines of text containing that
user-entered string and then prints them.
The text file in question contains names of University papers and their room numbers, quantity of students etc.
Example:
IBUS212 EALT006 1am 72 AL LI
BMSC241 MCLT102 2 pm 8 AL COOREY
My problem annoyingly enough seems to be that I can't think how one could compare the string entered to the lines of text being
scanned in the text file.
My latest go involved what you see in the code, scanning the examdata.txt file for a user-entered course number, using course.next();
by going with the example above it would be IBUS212. The task was to then to find all of the lines containing that number and print them out using
println (what I have tried with id and line) as well as the rest of that line eg: EALT006 1am 72 AL LI .
public void printCourse()
try
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your course ID: ");
input = user.nextLine();
Scanner course = new Scanner(new File("examdata.txt"));
course.next();
course.nextLine();
id = course.next();
line = course.nextLine();
if(input.equals(id))
System.out.println("Your course times are: " + id + "and" + line);
else
System.out.println("Your course does not exist.");
catch(IOException e)
System.out.print("File failure");
}Any advice/help/troubleshooting would be greatly appreciated.
Edited by: AUAN on Aug 13, 2009 9:43 AM
Edited by: AUAN on Aug 13, 2009 9:44 AM
Edited by: AUAN on Aug 13, 2009 9:49 AM
You'll want [to loop while|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html] the course Scanner has a next line and then print the line if it contains the entered text.
For useful methods you can check the Javadoc of String and Scanner (use your browser search on keywords like 'next' or 'contains' to find them).
Similar Messages
-
Finding words in a txt file!
Hi guys,
I have to write a program that opens a .txt file and looks for a specific word in the file and then prints out the entire line that word appears in. I have to use a String Tokenizer? I don't know how to write the program. All I have so far is a program that prints the entire txt document (or each line). I think String Tokenizer is involved in here somewhere but I don't know how to use it.
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.*;
public class Find
public static void main (String[] args) throws IOException
String line;
String name;
String file="find.txt";
StringTokenizer tokenizer;
FileReader x = new FileReader (file);
BufferedReader inFile = new BufferedReader (x);
line = inFile.readLine();
while (line != null)
tokenizer = new StringTokenizer (line);
word = tokenizer.nextToken("word");
System.out.println (line + "\n");
line = inFile.readLine();
inFile.close();
The text file Find.txt just has a few lines of text in it.
I want to make it so that I can look for a specific word in the text file and the resulting printout will be the entire line that the word appears in.
Any help would be great! Thanks!Your first post is very close to what you want:
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.*;
public class Find
public static void main (String[] args) throws IOException
String line;
String name;
String file="find.txt";
StringTokenizer tokenizer;
FileReader x = new FileReader (file);
BufferedReader inFile = new BufferedReader (x);
line = inFile.readLine();
while (line != null)
tokenizer = new StringTokenizer (line);
String word = tokenizer.nextToken();
if (word.equals("word")) // we are searchig for the String word
System.out.println ("found it! "+line + "\n");
line = inFile.readLine();
inFile.close();
[\code] -
Need help to add the words in a text file to an arraylist
I am new to java and I really need some help for my project.I want to add the words of a text file to an arraylist. The text file consist of words and the following set of punctuation marks {, . ; : } and spaces.
thanks in advance :-)I/O: [http://java.sun.com/docs/books/tutorial/essential/io/index.html]
lists and other collections: [http://java.sun.com/docs/books/tutorial/collections/index.html] -
To get a word in the text file
Hi,
I m beginner to java.
HOw i get a word in the text file.
I used this code, it is only display the all sentence which are available in the text file.
But , I need to print particular word (if it is available in that text file)
package com.beryl;
import java.io.*;
class FileReadTest {
public static void main (String[] args) {
FileReadTest f = new FileReadTest();
f.readMyFile();
void readMyFile() {
BufferedReader dis =null;
String record = null;
int recCount = 0;
try {
File f = new File("E:/hello/abc.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis
= new BufferedReader(new InputStreamReader(bis));
while ( (record=dis.readLine()) != null ) {
recCount++;
System.out.println(recCount + ": " + record);
} catch (IOException e) {
// catch io errors from FileInputStream or readLine()
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dis != null) {
try {
dis.close();
} catch (IOException ioe) {
Thanks & Regards,
kumarI used this code, it is only display the all
sentence which are available in the text file.
But , I need to print particular word (if it
is available in that text file)if
String.indexOf() -
Reading words from a text file
I have written code to store words in a text file. they appear in the text file as shown below.
word1
word2
word3
etc.
I want to read each word individually and store them in an array. Im trying to do it using a BufferedReader but it doesn't seem to work. The code for reading the words is shown below. Any suggestions would be appreciated.
try
FileReader reader = new FileReader("words.txt");
BufferedReader bReader = new BufferedReader(reader);
ArrayList words = new ArrayList();
String line;
while((line = bReader.readLine()) != null)
line = bReader.readLine();
words.add(line);
bReader.close();
catch (Exception e)
System.err.println ("Error writing to file");
}I think your code is wrong, because it Read two time from file,
your code like....
while((line = bReader.readLine()) != null)
line = bReader.readLine();
words.add(line);
you have to change the above code like
while((line = bReader.readLine()) != null)
words.add(line);
NOW ITS WORKING FINE,........... -
Hi,
I am trying to count word in my text file by using the Java code. Even though i am error in the code and don't know what sintaks to use. For example:
I have
school 4
bus 3
student 5
in a.txt
Another text file
bus 2
school 2
in b.txt
I want to display in new text file: c.txt
school 6 4 : a.txt 2 : b.txt
bus 5 3 : a.txt 2 : b.txt
student 5 5 : a.txt
Could you please advise,what sintak that i could use??
Thanks you..Use StringTokenizer object and HashMap Object
example
String str = (your text readed from file A)
StringTokinzed token = new StringTokinzed(str);
while (token.hasMoreTokens()) {
String word = token.nextToken()
Integer i = (Integer) hashmap.get(word);
if (i==null) {
i = new Integer(1);
}else
i++;
hashmap.put(word,i);
same code for B file
iterate through the hasmap and print all word with the count -
Replace/cut part of words from a text file.
Hello Hello everyone, I have a quick question. I have my text file that contains also words like ... let's say abc1, abc2 and so on, and I need to cut the c from the word, I need ab1, ab2.
Here is what I have started:
import java.util.*;
import java.io.*;
public class test
Vector<String> x = new Vector<String>();
public mergefiles() throws IOException
readAdd("test.txt");
write("testout.txt");
private void readAdd(String name) throws IOException
BufferedReader reader = new BufferedReader(new FileReader(name));
String line,all=new String();
while ((line = reader.readLine ()) != null)
all+=line+'\n';
reader.close ();
int posX=all.indexOf("X"); // x being like first word of the text file
if (all.length()-posX>0)
String between=all.substring(posX+3,all.length());
StringTokenizer st=new StringTokenizer(between," \n");
private void write(String name) throws IOException
BufferedWriter writer = new BufferedWriter(new FileWriter(name));
String s=new String();
if (x.size()>0)
s+="X"+'\n';
s+='\n';
writer.write(s);
writer.close();
public static void main(String[] args) throws IOException
new test();
}I am new to Java and I would really appreciate if you would be patient with me.
Thank you!I have tried in readAdd method something like:
int posX=all.indexOf("X"); // x being like first word of the text file
if (all.length()-posX>0)
string.replace("ab1","abc1");
} but still doesn't work, and this is not a really good ideea, in case that I have to replace 1000 of abci ...I should use a for in my write method:
String[] s=new String[2];
for(int i=0;i<word.length;i++)
BufferedWriter writer = new BufferedWriter(new FileWriter(testout.substring(0, testout.lastIndexOf("."))+(i+1)+".txt"));
writer.write(s);
writer.close();
But I not really sure if this is ok! Right now nothing is working
Thanks -
Finding strings in a text file?
Hi! i'm learning to read text files. what i want to do with this program is to find word 1-3, 2-4, 3-5... and write them in a system.out.println. i found a program that opens files and count words, lines and characters and tried to adjust it do find three-word strings.
i can compilate (hope that word exists) but when i run it, it says: Exception in thread "main" java.lang.NoSuchMethodError: main
anyone who knows what this could depend on?
This is what the code looks like:
import java.io.*;
import java.io.*;
import java.util.*; //tillagd f�r att removeFirst4 skall funka
import javax.swing.*; //tillagd f�r att removeFirst4 skall fungera
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.lang.*;
import javax.swing.*;
public class AttLaesaEnFil2 {
private static void samla(String name, BufferedReader in) throws
IOException {
String a;
WordExtractor b;
String c = " ";
String d;
WordExtractor e;
String f;
String g;
WordExtractor h;
String i;
String j;
String k;
String l;
String line;
do {
line = in.readLine();
if (line != null)
b = new WordExtractor(line);
c = b.getFirst();
d = b.getRest();
e = new WordExtractor(d);
f = e.getFirst();
g = e.getRest();
h = new WordExtractor(g);
i = h.getFirst();
j = h.getRest();
k = c + f + i;
l = c + " " + f + " " + i;
System.out.println("The first three words are: " + l);
a = b.getRest();
while (line != null);
System.out.println("Klart!");
private static void samla(String fileName) {
BufferedReader in = null;
try {
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
samla(fileName, in);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
private static void samla(String streamName, InputStream input) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(inputStreamReader);
samla(streamName, in);
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
Thanx in advance!this may be a stupid question but i'll give it a
shot. ...do i replace my private static void with
public static void or do a add the public?Whether you replace one of your methods or create a new one is up to you, but you have to have a method with this exact signature:
public static void main(String[] foo) {
}(The variable name can be different of course) -
Find Change through external text file
Hello folks
I am bit pretty in InDesign scripting so could you please look into this.
How can i change any particular text field in Indesign CS3 document from text file.
I do have find change script but for each InDesign document specific text file is assigned.
So each time i have to modify find change GREP property that is also repetetive of work. Is there any way to get find change information should be extract from external text file.
Many Tanks in advanceIn the FindChangeByList script, you could customize the function myFindFile(myFilePath) {...} as to search the FindChangeList text file in the document location rather than the script location. That's an example. The question is: given a document, where will you have the corresponding FindChangeList?
@+
Marc -
How to find largest number from text file
I am using the "Read from text file" block to read the data from my .txt file into labview. It is now in string format. I have many numbers in the file.
For example:
0.45
0.35
0.12
1.354
1.56
2.89
5.89
0.56
That is what a text file might look like. I want to find which of these numbers is largest, and do calculations with that number. I am having trouble with strings/number formats/arrays, etc. Thanks
Solved!
Go to Solution.The spreadsheet functions and VIs typically work on strings representing numbers separated by delimiters. This is a typical way to save a "spreadsheet" (of numbers) to a text file, for example .csv files. These are quite versatile and powerful functions. Spend a bit of time becoming familiar with them because you may find yourself using them a lot.
Lynn -
What is the best way of replacing words in a text file ?
i want to read in a text file and when i come across a certain word, i want to change it to something else. Whats the best way to do this ?
If i read in a line at a time, how would i only replace one word and not the rest of the line ?
thanksthanks it works !!! But i wrote the contents to a new file.
How do i overwrite the same file ? I put the the input and output file as the same location but it overwrites the original file with a blank one.
i guess i have to write into another buffer and read all lines first before overwriting the file right ? how should i do that ?
also, i only want to overwrite the file ONLY if applies replaceAll method, otherwise if no replacing takes place i dont want to keep updating the file everytime. -
Cannot copy and paste text in word,excel or text file
Cannot copy and paste in word,excel or in text file. It get paste in special charector.
Eg.
( )* +
( )* +Yesterday i update Yosemite and Adobe Photoshop CS6
i found error text message like you everytime when i used fontAwesome on Adobe Photoshop CS6 and then i found out to fix this problems Yeahh…
Try My Way to fix it out
-> copy The Text you want to use
-> paste your text (from your clipboard) To App TextEdit
-> then Copy again
-> back to Photoshop paste it on your document layout
-> Done -
Adding definitions to Specific Words within a PDF file
I have a client who wants me to add definitions to Glossary words throughout a PDF file. They want it to look like a "roll over" or when you click on the glossary word a definition pops up. Is there a way to do this in Acrobat 9 or it can't be done?
You can achieve this with one of my custom-made tools:
http://try67.blogspot.com/2008/11/acrobat-highlight-all-instances-of.html
If you set the comment color to "Transparent", it will act just like a pop-up that shows when you hover with the mouse over the text. -
How to search a String within a text file ?
************** text file ****************
Good bye good
bye good bye
good bye
good bye good
bye good
************** Input and Output ****************
Input: good bye
Output:
total strings Matched: 5
whichlinesmatched: 2
whichlinesmatched: 2
whichlinesmatched: 3
whichlinesmatched: 4
whichlinesmatched: 5
whichlinesmatched: 0
whichlinesmatched: 0
whichlinesmatched: 0
whichlinesmatched: 0
whichlinesmatched: 0
** but the desired output is 3, and only line 2, 3, 4 matched
** Could you please have further help about this? Thank you.
************** the codes****************
import java.io.*;
public class Tokenize{
public static void main( String args[] ){
int maxNumberOfLine = 1000; //the maximium number of line in data file for input
String fileName = "test"; // file name for data input
String stringForCount = "good bye"; // specified word for counting
int totalStringMatched = 0; // number of word matched
int[] whichLineMatched; // line number for each word matched
whichLineMatched = new int[maxNumberOfLine];
// Input string (stringForCount) has been stored in a string array, wordForCompare[]
// For example: stringForCount = "good bye"
int stringLength = 2;
String wordForCompare [] = { "good" , "bye" };
// wordForCompare[0] = good
// wordForCompare[1] = bye
int wordFromFile;
StreamTokenizer sttkr;
try{
FileInputStream inFile = new FileInputStream(fileName); //specifying the file to be opened
Reader rdr = new BufferedReader(new InputStreamReader(inFile)); //assigned a StreamTokenizer
sttkr = new StreamTokenizer(rdr);
sttkr.eolIsSignificant(false);
System.out.println("Searching for word : " + stringForCount );
while( (wordFromFile = sttkr.nextToken()) != StreamTokenizer.TT_EOF)
System.out.println( "going looping through file, token is: " + sttkr.sval );
if(sttkr.sval.equals(wordForCompare[0])){
if (stringLength == 1) {
totalStringMatched++;
whichLineMatched[totalStringMatched-1]=sttkr.lineno();
} else {
for (int p=1; p < stringLength; p++) {
wordFromFile = sttkr.nextToken();
System.out.println( sttkr.sval );
if (!(sttkr.sval.equals(wordForCompare[p])))
break;
else if (p==stringLength-1) {
totalStringMatched++;
whichLineMatched[totalStringMatched-1] = sttkr.lineno();
} // end of else
} // end of for-loop
} // end of else
System.out.println( " total strings Matched: " + totalStringMatched );
} // end of if
}//end of while for wordFromFile
for( int i = 0; i < 10; i++)
System.out.println( "whichlinesmatched: " + whichLineMatched<i> );
} catch(Exception e) {} //end of try
}A small change to roopa_sree's code, this code fails if there are multiple occurences of the search string in the same line. Make this small change to correct it,import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class WordCounter {
public static void main(String args[]) throws Exception {
if(args.length != 1) {
System.out.println("Invalid number of arguments!");
return;
String sourcefile = args[0];
String searchFor = "good bye";
int searchLength=searchFor.length();
String thisLine;
try {
BufferedReader bout = new BufferedReader (new FileReader (sourcefile));
String ffline = null;
int lcnt = 0;
int searchCount = 0;
while ((ffline = bout.readLine()) != null) {
lcnt++;
for(int searchIndex=0;searchIndex<ffline.length();) {
int index=ffline.indexOf(searchFor,searchIndex);
if(index!=-1) {
System.out.println("Line number " + lcnt);
searchCount++;
searchIndex+=index+searchLength;
} else {
break;
System.out.println("SearchCount = "+searchCount);
} catch(Exception e) {
System.out.println(e);
}Sudha -
HI all,
I have a text file in the following format
Part 1 Part 2
p2_f1 p2_f2 p2_f3 p2_f4 p2_f5 p2_f6
p1_f1 p1_f2 p1_f3 p1_f4 p1_f5 p1_f6
the above file is tab delimited
I would like to reorder the file in such a way that
when first word of the first line is " Part 1" then the second line should be
p1_f1 p1_f2 p1_f3 p1_f4 p1_f5 p1_f6
if the second word in the first line is " Part 2" then the third line should be
p2_f1 p2_f2 p2_f3 p2_f4 p2_f5 p2_f6
basically the lines after the first line in the text file should be sorted based on the words in the first line.
Any ideas on how I could proceed?
Thanks in advance.Hello ,
I have changed the code to initialize the hashmap.
My code is
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Reorder {
public static void main(String args[]) throws IOException {
FileInputStream fstream = null;
try {
fstream = new FileInputStream("E:\\Documents\\reorder.txt");
//Variable Declarations
String strLine;
Map<String, String> entries = new HashMap<String, String>();
ArrayList<String> partlist = new ArrayList<String>();
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
// Intialize tokenizer
String s = strLine;
StringTokenizer tokenizer = new StringTokenizer(s, "\t");
while (tokenizer.hasMoreTokens()) {
// add data to collection
partlist.add(tokenizer.nextToken());
// Sort The data
Collections.sort(partlist);
// Adding to hashmap
String key = strLine.substring(0, 2).replace("p", "Part ");
entries.put(key, strLine);
// System.out.println(partlist);
// Printing the hashmap
System.out.println(entries);
} catch (FileNotFoundException ex) {
Logger.getLogger(Reorder.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fstream.close();
} catch (IOException ex) {
Logger.getLogger(Reorder.class.getName()).log(Level.SEVERE, null, ex);
}But I have no clue as to how to add the read line part
String firstLine = readFirstLine();
String[] parts = split(line);and the write part
write(firstLine);
for(String part: parts){
write(entries.get(part));
}my output now looks like this
{Pa=Part 1 Part 2, Part 1=p1_f1 p1_f2 p1_f3 p1_f4 p1_f5 p1_f6, Part 2=p2_f1 p2_f2 p2_f3 p2_f4 p2_f5 p2_f6}
Thanks in advance.
Edited by: Spry.chipper on Dec 13, 2009 10:53 AM
Maybe you are looking for
-
Hi, maybe execute the expdp for some rows (for example 100) for all tables in one schema? I know that I can execute this for all rows, but not for a subset of rows. many thanks to all. Lain
-
Call of API for IBase contains errors
Dear All, We are using solution manager 4 with SP13.When i try to create a Ibase through Initiate Data transfer for ibase,i gives the following error. Call of API for IBase contains errors Message no. CRM_IB050 Diagnosis No import data was entered fo
-
Hi everyone, I just got my Playbook today and set up Bridge during the initial setup. I just noticed however that all the Bridge apps are in my "All" tab rather than in their own separate one, as I believe they should be based on some videos I've se
-
My stepdaughter downloaded a song from her ipod touch, I hold the main account on my desktop computer. It is saying that I am not authorized to play this song on my computer. I went and authorized my computer three times and click on the song and i
-
CSS backgroundImage and borderSkin conflict with ClassReference
I've spent several hours trying to figure this out. I have a programmatic skin that paints a gradient and sets it as a backgroundImage ClassReference in css. In that same stylesheet declaration I set the borderSkin to a ClassReference of a class th