Java:使用线程进行文件搜索

huangapple go评论87阅读模式
英文:

Java: Using Threads For File Searching

问题

我正在尝试使用线程来搜索一个已定义的文本文件。这个程序的作用是从用户那里获取命令行参数,根据他们的指定,在文件中使用单个线程或多个线程来查找指定的字符串。

所以一个命令行参数的示例可能是:

java threads m dog cat

这会将一个线程分配给 "dog",另一个线程分配给 "cat",并同时搜索文件中的这两个字符串。

然而,我的问题是我对线程不太熟悉。如果我的用户想要使用单线程,我该如何使用它来搜索文件呢?我希望发生的情况是,如果我的用户想要使用单线程,我希将一个单独的线程分配给这个词。所以这意味着我希望打开文件,搜索,找到字符串,然后关闭它。我应该如何做到这一点呢?我知道我不能两次使用同一个线程,所以我对如何完成这个任务感到有些困惑。我目前唯一的代码是:

public static void main(String[] args) {
    String arguments[] = new String[args.length];
    
    for(int i = 0; i < args.length; i++){
        arguments[i] = args[i];
    }
    
    if(args[0].equalsIgnoreCase("m")){
        
    } else if (args[0].equalsIgnoreCase("s")){
        
    }
}
英文:

I am trying to use threads in order to search an already defined text file. What this program should do is take in command line arguments from the user and depending on what they specify, search a file either using a single thread or multithreads in order to find specified strings.

So an example of a command line argument would be:

java threads m dog cat

What this would do is assign 1 thread to dog and 1 thread to cat and simultaneously search the file for both strings.

However, my issue is that I'm not entirely to familiar with threads. If my user wants to use a single-thread, how do I use that to search a file? What I want to happen is if my user wants to use single-threading, I would want a single thread to be assigned to the word. So this means I'd want to open the file, search, find the Strings, and then close it. How would I go about this? I know I cant use the same thread twice, so I'm a bit confused as how I would accomplish this. The only code I have so far is:

    public static void main(String[] args) {
    String arguments[] = new String[args.length];
    
    for(int i = 0; i &lt; args.length; i++){
        arguments[i] = args[i];
    }
    
    if(args[0].equalsIgnoreCase(&quot;m&quot;)){
        
    } else if (args[0].equalsIgnoreCase(&quot;s&quot;)){
        
    }
    
}

答案1

得分: 1

让我们首先创建搜索功能本身。我假设你所说的“搜索文件”是指找到包含某个词的所有行。

我将使用Java 8 Nio API,但你可以随意使用任何你想要的方法来读取文件。

public static void searchFile(File file, String query) throws IOException {
    Files.newBufferedReader(file.toPath())
        .lines().filter(line -> line.contains(query))
        .forEach(line -> System.out.println("Found " + query + ": " + line));
}

现在我们有了一个搜索文件的函数,让我们来使用它:

static File file = new File("yourfile.txt");

public static void main(String[] args) throws IOException {
    boolean async = args[0].equals("m"); // 如果args[0]是“m”,则使用多线程,否则使用单线程
    // 从args[1]开始迭代,而不是args[0]
    for (int i = 1; i < args.length; i++) {
        // 如果在异步模式下,为每个searchFile(...)调用启动一个新线程
        if (async) new Thread(() -> searchFile(file, args[i])).start();
        // 否则在当前线程中只是调用searchFile(...)
        else searchFile(file, args[i]);
    }
}

因此,你可以使用这种很酷的lambda语法来创建一个线程并在其中执行一些代码,method() 变成了 new Thread(() -> method()).start(),这基本上就是简单多线程的全部内容。

英文:

Let's start by creating the search function itself. I assume that by "searching a file" you mean finding all lines that contains some word.

I will use Java 8 Nio API, but you are free to use whatever you want to read files

public static void searchFile(File file, String query) throws IOException {
    Files.newBufferedReader(file.toPath())
        .lines().filter(line -&gt; line.contains(query))
        .forEach(line -&gt; System.out.println(&quot;Found &quot; + query + &quot;: &quot; + line));
}

Now we have a function that searches a file, let's use it:

static File file = new File(&quot;yourfile.txt&quot;);

public static void main(String[] args) throws IOException {
    boolean async = args[0].equals(&quot;m&quot;) // If args[0] is &quot;m&quot;, then use multithreading, else use single thread
    // Start iterating from args[1], not args[0]
    for (int i = 1; i &lt; args.length; i++) {
        // If in async mode, start a new thread for each searchFile(...) call
        if (async) new Thread(() -&gt; searchFile(file, args[i])).start();
        // Else just call searchFile(...) from current thread
        else searchFile(file, args[i]);
    }
}

So you have this cool lambda-syntax for creating a thread and executing some code in it, method() becomes new Thread(() -&gt; method()).start() and that's pretty much it for simple multithreading.

huangapple
  • 本文由 发表于 2020年9月23日 07:52:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64019134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定