Read file from directory in multiple threads and adding the digits [on hold]
I am working on a problem statement.The gist is
Extract multiple text files from a given directory.
Read each file in a separate thread and calculate the sum of the digits.
It means I have to create as many threads as number of files in
directories and calculate the sum of each file(File contains integers) in
separate threads.
I am stuck at : I am creating multiple threads inside a loop.But only
final variables are allowed inside a anonymous class.Making the variable
final will not iterate through all the files
**new de().commit(x);** // x should be final,but x is File type iterating
through Filearray
Code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
class de
{
void commit(File x)
{
int sum =0;
try{
FileInputStream fin = new FileInputStream(x);
byte[]b= new byte[5000];
fin.read(b);
for (byte digit:b)
{
sum=digit+sum;
}
System.out.println(sum);
}
catch(Exception e)
{
}}
public static void main (String args[])
{
File f = new File("C:\\Users\\Ankur\\workspace\\IO\\Numbers");
File []store = f.listFiles( new FilenameFilter()
{
public boolean accept(File f, String name)
{
return name.endsWith("txt");
}
}
);
for (File x: store)
{
Thread t = new Thread()
{
public void run ()
{
**new de().commit(x);**
}
};
}
}
}
No comments:
Post a Comment