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
Similar Messages
-
How to find a string in a text file
i'll have a text file in the following format and from this this type of file i've to get source URL i.e in the following file http://www.consolidatorshopper.com/patheo/Mall/prices.asp
and also i've to get POSTdata querystring i.e in the following file from cosolidateorname...... to &conid6=7
hope you people understood my problem
i'll be very thankful if u people help me
BEGIN HEADER
source:http://www.consolidatorshopper.com/patheo/Mall/prices.asp
POSTdata:consolidatorname=IF&AgentID=37344&SubAgentID=31030&LoginType=SUBAGNT&LoginConfirm=yes&ManageAccount=&CustomAccount=6&PALPowerSearch=2&ShowConsolidatorsOnPricesPage=0&PALHomePage=http://www.consolidatorshopper.com&PMarkup=0&PALLoginText=<B>Specific%20Consolidator%20Search:</B><BR>%20Click%20on%20the%20desired%20region%20on%20the%20map.<BR><BR><B>Power%20Search:</B><BR>To%20search%20all%20consolidators%20simultaneously%20click%20on%20the%20button%20below.%20However,%20not%20all%20consolidators%20currently%20participate%20in%20the%20Power%20Search.&PALrelativeLoginURL=&PALrelativeBookingURL=&[email protected]&SiteID=3&MallOwnerMarkupFlat=&conidselected=16&powersearch=2&iscontinentselected=1&Continent=USDomestic&Source=1&CRSName=AP&[email protected]&ConsolidatorURL=http://www.patheo.com&ConsolidatorPhone=714-677-0929&ConsolidatorFax=714-908-7110&ConsolidatorFullName=Patheo&noofconselected=7&amadeusconidstring=&flagamadeus=1&PowerSearchConsolidatorstring=&PublishedCRS=&APPseudoCity=&SBPseudoCity=&AMLogin=&assword=&AMCorpID=&AMCatNo=&ConsolidatorFares=1&PublishedFares=0&PublishedConsolidator=0&PreferencedConsolidator=&Arciata=&dep_from=MIA&dep_to=LON&ret_from=LON&ret_to=MIA&dep_month=08&dep_day=08&dep_year=2003&dep_weekday=Thu&txtLengthOfStay=7&ret_month=08&ret_day=15&ret_year=2003&ret_weekday=Thu&dep_time=12P&ret_time=12P&triptype=RoundTrip&simpleclass=Economy&srchAirline=&adultno=1&childno=0&infantno=0&conid0=11&conid1=97&conid2=1&conid3=86&conid4=5&conid5=94&conid6=7
BEGIN INFORMATION
TimeStamp:datetime:date()
BEGIN ACTION
startafter:<tr valign=middle bordercolor=#ffffff>endat:</table>
pattern:<font face='Arial, Helvetica, sans-serif' size='2'>[^<]*
$1:SYMBOL:TEXT
$2:INDEX:TEXT
$3:CLOSING:FLOAT
$4:CHANGE:FLOAT:StripHTMLTags()
$5:CHANGEPCT:FLOAT:StripHTMLTags()
BEGIN DOHi, this is my fourth post to forum.java.sun.com and my final one for the day, so I can allow feedback to emerge on my compliance or lack thereof with the conventions of the board.
Fortunately, I have picked up the skill of telepathy and so am able to answer your question. :)
In your processLine(String line) method or equivalent, you can do something like this:
if (line.indexOf("source:") == 0) {
source = line.substring(6, line.length());
} else if (line.indexOf("POSTdata:") == 0) {
postdata = line.substring(9, line.length()); -
How to replace a string in a text file?
Hi All,
i read one text file and based on that i replaced the old character with the new string but it doesnt works.do any one of you have idea on this?
My Code:
String newPassword=(String) getInputText1().getValue();
String password=(String)getSimNo().getValue();
String sampleText = (String) getMobileNo().getValue();
FileReader fr =new FileReader("c:/newLogin.txt");
BufferedReader br =new BufferedReader(fr);
String record=br.readLine();
while (record !=null)
String[] afterSplit=record.split(":");
for (int p = 0; p < 1; p++) {
String userName=afterSplit[1];
String passWord=afterSplit[3];
if(userText.equals(userName) && password.equals(passWord)) {
passWord.replaceAll(passWord,newPassword);
System.out.println("password: " + password +" changed to : "+ newPassword +" successfully");
record =br.readLine();
sample fiile in the text:
userName:sebas:password:navin
userName:sebas1:password:navin1All readLine does is copy a line of the file into a local variable. Change the copy as you will, the file won't change.
You need to write a new version of the file, with the altered lines. Then, if required, you can delete the original file and rename the new file to the old file name. -
How to Search document by using Long text description contents in SAPEasy DMS
Hi,
How to Search document by using Long text description contents in SAPEasy DMS
Regards,
Shrikant ShindeHi Alfredo,
Thanks for reply..Will you please explain in brief what are the OCR program and workflow.
Will you please send me any docs on [email protected]
Thanks
shiv. -
How to search a string from the database?
how to search a string from the database? starting with some character
If you're trying to do this in a SELECT, you can use the LIKE verb in your WHERE clause.
Here's an Example
SELECT obj_name FROM tadir
INTO prog
WHERE pgmid = 'R3TR'
AND object = 'PROG'
AND obj_name LIKE 'Z%'.
In this case it will select every row that obj_name starts with Z.
If you wanted to find every row that the field obj_name contains say... 'WIN' you use LIKE '%WIN%'.
Edited by: Paul Chapman on Apr 22, 2008 12:32 PM -
How to write Strings in a text file with BufferedWriter
I've got a Vector object full of Strings objects, I'm interested in wrinting these Strings in a text file with a BufferedWriter , I would apreciate some code, thank you
http://java.sun.com/products/jdk/1.2/docs/api/java/io/BufferedWriter.html
"PrintWriter out = new PrintWriter(new BufferedWriter((new FileWriter("foo.out")));" -
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 AMYou'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). -
Reading Each String From a text File
Hello everyone...,
I've a doubt in File...cos am not aware of File.....Could anyone
plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help meThe Java� Tutorials > Essential Classes: Basic I/O
-
How to read the content of a text file (by character)?
Guys,
Good day!
I'm back just need again your help. Is there anyone knows how to read the content of a text file not by line but by character.
Please help me. Thank you so much in advance.
Jojohttp://java.sun.com/javase/6/docs/api/index.html
package java.io
InputStream.read(): int
Reads the next byte of data from the input stream.
Implementation:
InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. -
How to get summary columns in delimited text file
How to get summary columns in delimited text file
I am trying to generate a delimited text file output with delimited_hdr = no.The report is a Group above report with summary columns at the bottom.In the text file the headers are not getting repeated & thats ok.The problem is the summary data is getting repeated for each row of data.Is there a way where i will get all the data & summary data will get displayed only once.I have to import the delimited text file in excel spreadsheet.Sorry there were a typos :
When I used desformat=DELIMITEDDATA with desttype=FILE, I get error "unknown printer driver DELIMITEDDATA". When you look for help, DELIMITED is not even listed as one of the values for DESTFORMAT. But if you scroll down and look for DELIMITER it says , this works only in conjuction with DESTFORMAT=DELIMITED !!!!!!??!! This is in 9i.
Has this thing worked for anybody ? Can anyone please tell if they were able to suppress the sumary columns or the parent columns of a master-detail data for that matter ? -
How do i split content from the text file using tab and spaces...?
Hi.. Just want to ask help to all the experts. Im new in java and i have this problem on how to split the contents of the text file. ill show you the contents in order to let you see what i mean.
FileName: COL.txt
AcctNo AcctName Primary Secondary Status Opendate
121244 IPI Company Noel Jose Active 12/05/2007
As you can see the content i want to split it per column.. Please help meJose_Noel wrote:
Hi prometheuzz,
What do you mean by one thread...?You created two threads* with the same question in it. That way, people might end up giving you an answer that has already been posted in your other thread: thus wasting that person's time.
Just don't create multiple threads with the same question please.
* a thread is a post here at the forum -
How to search a string in some folder.
Hi ,
In my application users will upload some pdf,xls files to server. files will be saved in server. From the front end can search on all files with some specific string. If that string is there in any of the file, user has to get link to download that file and the text just before and after that user string. Its like how we get in google. This type of search we need to implement, Could any one please let me know how to implement, any free API are there in java. Please its urgent, help on this.
Thanks
Mohanuser594301 wrote:
I have 2 columns in a table. entry_no and msg_txt. entry_no is number(12) and msg_txt is LONG. I want to search one string in msg_txt. How can I write a query for this ?You can't write a query for this. The only thinks you can do with a long in a query is put something in and take it out again - with diffiuclty, usually.
You can write a PL/SQL function to do this for you if necessary. The function will have to perform the search directly if the long < 32760 bytes or use DBMS_SQL to break the LONG up into 32760 byte segments that can then be manually searched. If you are lucky someone has done this already and posted the code online. Either way the solution will be slow and probably painful to implement.
If possible convert your data to a CLOB and use DBMS_CLOB to find the data you need. -
How do I apply style within a text frame linked object
I'm selecting the text frame in the object I want to apply an object style
A script can be written
within a text frame the linked object (selected text frame)
how object style is appliedHi
All you need is
app.selection[0].appliedObjectStyle = app.activeDocument.objectStyles.itemByName ("Trevors Object Style");
The below snippet will apply the style to all the anchored objects in the selection or document
var doc = app.properties.activeDocument,
myOnjectStyle = doc.objectStyles.itemByName ("Trevors Object Style"),
myObjects, l;
if (!myOnjectStyle.isValid) {
alert ("Either add an Object Style Called:\nTrevors Object Style\nOr Make Significant Changes to The Script");
quit ();
app.findTextPreferences = app.changeTextPreferences = null;
app.findTextPreferences.findWhat = "^a";
myObjects = (app.selection && app.selection[0]).findText () || doc.findText ();
l = myObjects.length;
while(l--) myObjects[l].textFrames[0].appliedObjectStyle = myOnjectStyle;
HTH
Trevor -
How do i read a context of text file within Dynamic Page of portal ?
Dear sir,
I have a text file in client computer. I hope i can transfer the context words of this text file to oracle database. How do i coding this script in dynamic page of portal?
Can Oaracle 9ias script read and draw the context of a document. Thank you ver much!
Ghia LiuGreat questions, Rik, and I understand how this might seem bizarre. Here's the story... these 2500 files were authored with a built-in authoring tool of our current knowledge management system. This KMS is about to be replaced with a new one and because the new KMS needs content within the <head> tag instead of where it was in the <body> tag and redefined as meta data, I repuposed the content in those files using Dreamweaver and regular expressions. However, the one remaining <h3> and <p> content is in the middle of the newly tagged meta data and it must be moved from the <head> area and into the <body> area.
Because these were authored in the built-in KMS authoring tool, there is no style sheet and no, we do not manage our content with a CMS.
You are correct, if the <h3> and <p> were at the end of the data, I could simply move the </head> and <body> tags, but unfortunately that is not the case. They are consistenly in the same place in all 2500 files, but in the middle of the data. Following is an example:
<html>
<head>
<title>Title here</title>
<meta name="XYZ" content="Something here...">
<h3> Blah blah</h3> <p>More blah blah</p>
<meta name="123" content="More somthing here">
<meta name="456" content="More somthing here">
</head>
<body>
</body>
</html>
Again, I can find the block using a regular expression <h3>(.*?)</p>, but dont know what to do after that.
I've been told that perl or grep might do the needed task, but that requires outside resources and I have no budget for that.
Any suggestions are greatly appreciated.
thanks,
Rick -
How to output strings to an text file and excel file
Hi guys,
I am writing a simple application taht process some string inputs from user using a simple GUI. The GUI consists of a series of
textfields which the user can enter names, age, addresses....etc
Once they complete filling up that GUI form, they click SUBMIT. All the values will then be read. These strings are then required to be output to 2 files
1. To a text file which I can open it and read it anytime I wish.
2. To an excel file which follows a specific format. That is, all names will be written to column B, all ages will be written to column C...etc
The programme is expected to keep running allow the user to enter details of multiple persons(some 300 sets of data of different persons) until he clicks on End program.
Please advise how I can output the strings to
1. Text file
2. Excel file.
Many many thanks. I need this for one of my project which is due so so soon...... :((
Regards
David1. Text file
See link to "Documentation - Tutorials" on the left
side of this page.
2. Excel file
Dont try to write the real excel format (if you want
to do it soon).
- write data to a plain text file.
- Use tab stops for separation of values.
- Name file as excel file. (*.xls)
If you double click this file, excel will import data
and insert it to a table in the right order by
itself.
Excel can save this as real .xls now.
Anyone here with a better idea? (Try to learn by
myself)good thing to know for the excel tip :)
thx
Maybe you are looking for
-
I can not type a url in the browser window when I open a new tab. Why not?
I open a new tab click in browser window and see cursor but it does not blink. If I click in google search window it works fine. I can redirect using bookmarks but if I want to just type it in, it acts blocked or locked. Could I have done something t
-
Where can I download missing "Minion Pro" and "Myriad Pro" type fonts?
For some reason I have fewer Minion Pro & Myriad Pro type fonts on my Windows 7 home computer than I do on my Windows 7 work computer, and I'm trying to do the same commercial project with both of them. I have subscribed to Creative Cloud for over a
-
How much does Premiere Pro and After Effects rely on the hard drive it's installed on?
This may be a really dumb question, but how much does Premiere Pro and After Effects rely on the hard drive it's installed on if all your video files, assets, disk cache, etc are on different drives than the one the program itself is installed on? Th
-
Why changes are not visible in alternate profit center heirarchy?
Hi I did changes in the master data of profit center. I chaged the profit center group in the masterdata of profit center & the same change is visible in the standard heirachy but the changes are not visible in the alternative heirarchy. I think it s
-
Language translation for text elements.
Hey ABAP Gurus, I am having a problem, with translation of text elements in korean language. I have translated the TEs in korean, but they dont appear in ko, they appear in Portuguese... I have tried using se63, and se80 for the translation... Am I m