Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / Java

Scanning File for a Particular String or Character (Searching)

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
14 Oct 2014MIT1 min read 11K   3   4
Scanning file for particular string or character (Searching)

Fews days ago, I saw a post on Stack Overflow in which the user wanted to search the file content. I didn’t answer that post because it was off-topic for that website. But, now I wanted to share the code for that particular action to the public.

I was working on this project since today morning and I finally came up with the code for that. Actually not only me, some other helpful fellows from the Stack Overflow community too. I had a problem in my code but the guys there helped me and made me move on to my right track. A warm thank you to them.

Well, the code was simple and small in size although it was a powerful code. I used a simple File.txt file in the res folder and then the coding began. Here is the file content.

Ok, here is some text!

Actually, this file is created to test the validity of the Java application.

Java is my favourite programming language. I can say that, because for my every tag

on Stack Overflow, I have no enough score. But for Java I have scored enough!

And I think I can score even more :)

Wish me luck!

Then I wrote the code to search this file for the character or a string the user would input. Definitely, I would search for a String, not a character. Because character would always be present in the file somewhere.

The code is:

Java
package com.wordpress.thevsorganisation.java.find_words;

import java.io.*;
import java.util.Scanner;

public class Main {
   public static void main (String[] args) throws IOException {
   // Only write the output here!!!
   System.out.print("Write the character to be found in the File: ");
   Scanner sc = new Scanner(System.in);
   String character = sc.next();
   // Find the character
   System.out.println("Searching now...");
   getCharacterLocation(character);
   // Close the resource!
   sc.close();
 }
 
 // Get character and all other methods would be here...
 public static void getCharacterLocation (String character) throws IOException {
   File file = new File("res/File.txt");
   Scanner sc = new Scanner(file);
   int lineNumber = 0;
   int totalLines = 0;
   boolean found = false;
   // First get the total number of lines
   while(sc.hasNextLine()) {
   totalLines++;
   sc.nextLine();
   }
   int[] lineNumbers = new int[totalLines];
   int lineIndex = 0;
   sc.close();
   sc = new Scanner(file);
   while(sc.hasNextLine()) {
     // Until the end
     /* Get each of the character, I mean string from
     * each of the line... */
     String characterInLine = sc.nextLine().toLowerCase();
     if(characterInLine.indexOf(character.toLowerCase()) != -1) {
       found = true;
     }
     lineNumber++;
     if(sc.hasNextLine())
       sc.nextLine();
     }
     // All done! Now post that.
     if(found) {
       // Something found! :D
       System.out.print("'" + character + "' was found in the file!");
     } else {
       // Nope didn't found a f***!
       System.out.println("Sorry, '" + character + 
       "' didn't match any character in file  .");
     }
   sc.close();
 }
}

Share the code, and do remember to ask for more!

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Glenn Sugden15-Oct-14 9:22
Glenn Sugden15-Oct-14 9:22 
GeneralRe: My vote of 3 Pin
Afzaal Ahmad Zeeshan8-Nov-14 9:47
professionalAfzaal Ahmad Zeeshan8-Nov-14 9:47 
QuestionWhat wrong with built in functions? Did I miss something? Pin
Sing Abend15-Oct-14 6:45
professionalSing Abend15-Oct-14 6:45 
AnswerRe: What wrong with built in functions? Did I miss something? Pin
Afzaal Ahmad Zeeshan8-Nov-14 9:48
professionalAfzaal Ahmad Zeeshan8-Nov-14 9:48 
No sir, you're perfectly right! Built-in functions are correct.

But this is a blog post that I wrote for the questions that arose continously on Stack Overflow regarding "Searching for a String in Java".

Thanks.
You only get one shot, do not miss your chance to blow
This opportunity comes once in a lifetime, yo - Eminem
~! Firewall !~

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.