I need to read two files by using multiple threads and print the content of the files in the console.The user will enter the file paths and use the threads to read the contents of the files. I have a hard time understanding files. Can anyone just suggest me what should be done in the run method?
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();
}
}
}
The
runmethod is meant to contain the code which is executed by that thread. So, as you want to read two files from two different threads, you’ll need to userunfor doing whatever you’re doing inReadFilemethod.Note that you’ll need to create an instance of
Ch3Ex4class and invoke thestartmethod in order to start to start a new thread.EDIT: In that case, you can use a
BufferedReaderinside therunmethod like this: (From mkyong‘s website)