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:
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 {
System.out.print("Write the character to be found in the File: ");
Scanner sc = new Scanner(System.in);
String character = sc.next();
System.out.println("Searching now...");
getCharacterLocation(character);
sc.close();
}
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;
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
sc.close();
sc = new Scanner(file);
while(sc.hasNextLine()) {
String characterInLine = sc.nextLine().toLowerCase();
if(characterInLine.indexOf(character.toLowerCase()) != -1) {
found = true;
}
lineNumber++;
if(sc.hasNextLine())
sc.nextLine();
}
if(found) {
System.out.print("'" + character + "' was found in the file!");
} else {
System.out.println("Sorry, '" + character +
"' didn't match any character in file .");
}
sc.close();
}
}
Share the code, and do remember to ask for more!