
How to Write a Java program which read in a number of text files. It will use a thread to one file. Each line in the file will be put into a fixed size buffers of strings. The buffer can store at most 10 strings. The buffer is operated as a queue in the first-in-first-out order. There will be the same number of threads as the number of the files to get strings from the buffer. After getting the strings from the buffer, the threads will print them out in the standard output. The program should be started like this:
java readFiles file1 file2 file3
where file1, file2, etc are name of the files to be read. In this example, the program should create three threads for reading the file and three threads for getting the strings out of the queue and printing them

Hi Friend,
Try the following code:
import java.io.*;
class ReadFileUsingThread
{
public void readFromFile(final String f1,final String f2,final String f3) {
Runnable readRun1 = new Runnable() {
public void run() {
StringBuffer buffer1=new StringBuffer(10);
try{
Thread.sleep(5000);
File inputFile = new File(f1);
FileInputStream in = new FileInputStream(inputFile);
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
buffer1.append(new String(bt));
System.out.println(buffer1.toString());
} catch(Exception ex) {
}
}
};
Thread thread1 = new Thread(readRun1);
thread1.start();
Runnable readRun2 = new Runnable() {
public void run() {
StringBuffer buffer2=new StringBuffer(10);
try{
Thread.sleep(5000);
File inputFile = new File(f2);
FileInputStream in = new FileInputStream(inputFile);
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
buffer2.append(new String(bt));
System.out.println(buffer2.toString());
} catch(Exception ex) {
}
}
};
Thread thread2 = new Thread(readRun2);
thread2.start();
Runnable readRun3 = new Runnable() {
public void run() {
try{
StringBuffer buffer3=new StringBuffer(10);
Thread.sleep(5000);
File inputFile = new File(f3);
FileInputStream in = new FileInputStream(inputFile);
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
buffer3.append(new String(bt));
System.out.println(buffer3.toString());
} catch(Exception ex) {
}
}
};
Thread thread3 = new Thread(readRun3);
thread3.start();
}
public static void main(String[] args)
{
ReadFileUsingThread files=new ReadFileUsingThread();
String f1="C:/data.txt",f2="C:/employee.txt",f3="C:/hello.txt";
files.readFromFile(f1,f2,f3);
}
}
Hope that it will be helpful for you.
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.