Skip to content
Advertisement

Converting serially reading multiple files to reading them in parallel? [closed]

Following code in Java reads multiple files one after another serially and it works well till here. (The files are JSON and at this step they are stored in a String/Buffer without parsing.)

JavaScript

How to read those files in parallel by using Threads ?

I could not match Multithreading to above code and every time got errors.

Advertisement

Answer

I’ve not tested this code directly (as I don’t have a bunch of files to read), but the basic idea would be to do something like…

JavaScript

This will basically execute a series of Callables and wait for them all to complete, at which time, you can then read the results (or errors)

See the Executors trail for more details

Tested and verified version…

So, I dumped a series of files into a the Files folder at the root of my working directory, modified the above example to list all the files in that directory and read them….

JavaScript

And this works just fine and I have no issue.

java.io.FileNotFoundException: Filesfile0.json is a localised issue you are going to have to solve. Does file0.json actually exist? Does it exist in the Files directory? Is the Files directory in the root of the working directory when the program is executed?

None of these issues can be solved by us, as we don’t have access to your environment

Test #3

I then renamed all the files in my Files directory to file{x}.json using…

JavaScript

And the modified the example slightly to include a File#exists report…

JavaScript

Which prints

JavaScript

which all worked without issues

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement