简体   繁体   English

我需要计算使用扫描仪和JFIleChooser在文件中出现子字符串的次数

[英]I need to count the number of times a substring occurs in a file using scanner and JFIleChooser

I am trying to learn Java and I want to know how I can count the number of times a substring occurs in a chosen text file and have it output to the console. 我正在尝试学习Java,我想知道如何计算所选文本文件中子字符串出现的次数并将其输出到控制台。 For example say I used JFileChooser to grab a text file from my computer and I wanted to know how many times the substring "if" or "ot" occurred in the file. 例如,假设我使用JFileChooser从计算机中获取文本文件,并且想知道子字符串“ if”或“ ot”在文件中出现了多少次。 Any help would be appreciated! 任何帮助,将不胜感激!

import java.util.Scanner;
import javax.swing.JFileChooser;

public class FileReader {
    public static void main(String[] args) {
        int count = 0;
        JFileChooser chooser = new JFileChooser();
        Scanner in = new Scanner(/* How do I get the file? */);
        { // file read
            while (in.hasNext()) {
                count++;
                in.next();
            }
            System.out.println("The word count is " + count);
        }
    }
}

The first thing you need to do is to actually display the open dialog. 您需要做的第一件事是实际显示打开的对话框。 You can do this with the method showOpenDialog . 您可以使用showOpenDialog方法执行此showOpenDialog Afterwards, you want to get the selected file from the chooser by calling chooser.getSelectedFile() . 之后,您要通过调用chooser.getSelectedFile()从选择器中获取所选文件。 This file is stored in the variable file . 该文件存储在变量file

Now, you need to open the file for reading. 现在,您需要打开文件进行读取。 In Java you do this with a FileInputStream . 在Java中,您可以使用FileInputStream进行此操作。 You can pass this to the constructor of the class Scanner , together with the character encoding how you expect the file to be encoded. 您可以将其与字符编码一起传递给Scanner类的构造函数,并期望如何编码文件。

Now, you have the scanner initialized. 现在,您已初始化扫描仪。 To ensure, that all resources are released after you are done, you can use Java's try-with-resource statement, which is of the form 为确保完成后释放所有资源,可以使用Java的try-with-resource语句,其形式为

try (/* open resource */) {/* use resource */}

In this case, the scanner is the resource which should be closed. 在这种情况下,扫描程序是应关闭的资源。 When the scanner is closed, the file is closed. 关闭扫描仪后,文件将关闭。

Then, you only want to count the occurrences of the words "if" and "ot". 然后,您只想计算单词“ if”和“ ot”的出现次数。 To do this, you first read the word. 为此,您首先要阅读单词。 Afterwards, check whether it is equal to one of the expected words. 然后,检查它是否等于期望的单词之一。 If it is, you increase the counter. 如果是,则增加计数器。 Please note, that in Java you cannot compare Strings using the == operator. 请注意,在Java中,不能使用==运算符比较字符串。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.JFileChooser;

public class FileReader {
    public static void main(String[] args) throws FileNotFoundException {
        int count = 0;
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File file = chooser.getSelectedFile();
        try (Scanner in = new Scanner(new FileInputStream(file), "UTF-8")) {
            while (in.hasNext()) {
                String token = in.next();
                if (token.equals("if") || token.equals("ot")) {
                    count++;
                }
            }
        }
        System.out.println("The word count is " + count);
    }
}

Instead of handling streams with files you can simply use Apache's StringUtils & FileUtils to count your matching words as like follows, 除了使用文件处理流之外,您还可以使用Apache的StringUtils和FileUtils来对匹配的单词进行计数,如下所示,

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.FileUtils

import javax.swing.JFileChooser;

public class FileReader 
{
    public static void main(String[] args) 
    {
        int count = 0;
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File file = chooser.getSelectedFile();
        try
        {
            count = StringUtils.countMatches(FileUtils.readFileToString(file),"Search_String or Search_Character");
            count += StringUtils.countMatches(FileUtils.readFileToString(file),"Search_String or Search_Character");
        }
        catch(Exception e)
        {
            System.out.println("Error :" + e);
        }
        System.out.println("The word count is " + count);
    }
}

You can try like this also. 您也可以这样尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM