65.9K
CodeProject 正在变化。 阅读更多。
Home

扫描文件以查找特定字符串或字符(搜索)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2投票s)

2014 年 10 月 14 日

MIT

1分钟阅读

viewsIcon

12010

扫描文件以查找特定字符串或字符(搜索)。

几天前,我在 Stack Overflow 上看到一个帖子,用户想搜索文件内容。我没有回复那个帖子,因为它与该网站的主题无关。但是,我现在想将这段代码分享给公众。

我从今天早上开始就在这个项目上工作,最终完成了代码。实际上,不仅是我,还有其他一些乐于助人的 Stack Overflow 社区成员。我的代码中遇到了一些问题,但他们帮助我走上了正确的方向。衷心感谢他们。

这段代码很简单,而且体积很小,但功能却很强大。我使用了 res 文件夹中的一个简单的 File.txt 文件,然后开始编写代码。以下是文件内容。

好的,这里有一些文本!

实际上,这个文件是用来测试 Java 应用程序有效性的。

Java 是我最喜欢的编程语言。我可以这么说,因为我在 Stack Overflow 上几乎每个标签

都没有足够的积分。但对于 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();
 }
}

分享代码,并记住多多提问!

© . All rights reserved.