Java searching for string in file




















Learn more. Searching through a text file java Ask Question. Asked 6 years, 9 months ago. Active 4 years, 7 months ago. Viewed 40k times. It would be better if you mention few lines from "data. It's okay, I figured out the issue. The issue was at kb. It should be kb. Add a comment. Active Oldest Votes. File; import java. FileNotFoundException; import java. How do i go about parsing the file with scanner instead of some string "am". You can replace that with anything you want.

You can also ask the user input a string for you and pass that as a param in the method. I did include scanner as a parameter but then it don't work. The arguments of the function parseFile are two String objects. Of course this search method can slow down for huge text files since we are doing a sequential process of the file. So for experimental purposes I suggest that you start with a file that has no more than a few hundred lines and then expand it when you want to do some serious processing.

If the text file gets too big, you might want to look at an indexed approach. Maybe we will cover this in another entry… who knows! Read through the in-code comments of the example above and see how this is put together. Each step has been documented so that you can put the pieces together and come up with an idea of what the program is doing. Feel free to edit the code as you see fit and make whatever modifications you want to it. Just keep in mind this is ideal searching for text files and not exactly what you want to do for binary files.

Those baddies will have to be handled another day. After all, the super criminals are not easily caught! So the next time you are in a dark room at night and no where else to turn for learning file handling in Java, have no fear, DIC and Martyr2 is here! Thank you for reading! Desktop Programming File Handling Java. He has been a programmer for over 23 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world.

He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including. Intersection of LinkedLists Using Java. Comparators in Java Prepare to Compare.

Next Post ». Topic Categories. Here in this example, I read input file line by line searching for the given string or phrase. The code uses Pattern and Matcher classes to search for the string.

If a line contains the string we are looking for we store its line number in a List. At the end, the method returns the List of Integer objects depicting the lines of the file that have the given string. If the file does not contain given string an appropriate message will be printed.

Nuebee August 12, pm. Very good and helpful tips…. Thanks ….. Mukesh December 29, am.



0コメント

  • 1000 / 1000