java - 文件和多线程

标签 java eclipse multithreading

我需要使用多个线程读取两个文件,并在控制台中打印文件的内容。用户将输入文件路径并使用线程读取文件的内容。我很难理解文件。谁能建议我在 run 方法中应该做什么?

import java.io.*;

public class Ch3Ex4 implements Runnable
 {
  public void ReadFile(String str,Thread thread)
   {
    try
     {
      File inputFile = new File(str);
      FileInputStream in = new FileInputStream(inputFile);
     }
    catch(Exception e)
    {
        e.printStackTrace();
    }
  } 
    public void run()
      {

      } 

 public static void main (String[] args)
  {
    try
    {
    Ch3Ex4 obj = new Ch3Ex4();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the two file paths:");
    String s1 = br.readLine();
    String s2 = br.readLine();
    Thread thread1 = new Thread(obj);
    Thread thread2 = new Thread(obj);
    obj.ReadFile(s1, thread1);
    obj.ReadFile(s2, thread2);
    thread1.start();
    thread2.start();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
  }
 }

最佳答案

run 方法旨在包含由该线程执行的代码。因此,当您想要从两个不同的线程读取两个文件时,您需要使用 run 来执行您在 ReadFile 方法中所做的任何操作。

请注意,您需要创建 Ch3Ex4 类的实例并调用 start 方法才能开始启动新线程。

编辑:在这种情况下,您可以在 run 方法中使用 BufferedReader,如下所示:(来自 mkyong 的网站)

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:\\testing.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

关于java - 文件和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14303050/

相关文章:

java - 在 Apache POI 中读取 10 MB 文件

android - 将 Eclipse 项目导入 Android Studio 时出错

linux - 内核编程 - 互斥量

java - Java 中的服务器客户端 : could not start client

java - 状态栏颜色不会随 AppCompatActivity 改变

android - Eclipse 和 Android 和类路径 : bin and target

java - 是否有用于 Eclipse 3.4 的 jface 数据绑定(bind)框架的良好示例和文档?

c++11 注册缓存线程安全

java - Android 使用多线程更快地下载文件

java - Jedis Subscribe thread get Connection time out exception 每一个固定的时间间隔