在Stack Overflow社区中,遇到了一个关于Java文件搜索功能的讨论,虽然它与那个网站的讨论主题不符,但决定在这里分享相关的代码。这个项目从今天早上开始,经过一番努力,最终完成了代码。不仅是,Stack Overflow社区中的其他热心成员也提供了帮助,让得以继续前进。在此,要向他们表示衷心的感谢。
代码本身简单而小巧,但功能强大。使用了位于res文件夹中的一个名为File.txt的文件,然后开始了编码工作。以下是该文件的内容:
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!
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();
}
}