Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9020451
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T05:01:13+00:00 2026-06-16T05:01:13+00:00

import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel;

  • 0
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test6 implements Runnable {

    private File file;
    private int totalNumberOfFiles = 0;
    private static int nextFile = -1;
    private static ArrayList<String> allFilesArrayList = new ArrayList<String>();
    private static ExecutorService executorService = null;

    public Test6(File file) {
        this.file = file;
    }

    private String readFileToString(String fileAddress) {
        FileInputStream stream = null;
        MappedByteBuffer bb = null;
        String stringFromFile = "";
        try {
            stream = new FileInputStream(new File(fileAddress));
            FileChannel fc = stream.getChannel();
            bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            /* Instead of using default, pass in a decoder. */
            stringFromFile = Charset.defaultCharset().decode(bb).toString();
        } catch (IOException e) {
            System.out.println("readFileToString IOException");
            e.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                System.out.println("readFileToString IOException");
                e.printStackTrace();
            }
        }
        return stringFromFile;
    }

    private void toFile(String message, String fileName) {
        try {
            FileWriter fstream = new FileWriter("C:/Users/Nomi/Desktop/Workspace2/Test6/TestWritten/" + fileName);
            System.out.println("printing to file: ".concat(fileName));
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(message);
            out.close();
        } catch (Exception e) {
            System.out.println("toFile() Exception");
            System.err.println("Error: " + e.getMessage());
        }
    }

//  private void listFilesForFolder(final File fileOrFolder) {
//      String temp = "";
//      if (fileOrFolder.isDirectory()) {
//          for (final File fileEntry : fileOrFolder.listFiles()) {
//              if (fileEntry.isFile()) {
//                  temp = fileEntry.getName();
//                  toFile(readFileToString(temp), "Copy".concat(temp));
//              }
//          }
//      }
//      if (fileOrFolder.isFile()) {
//          temp = fileOrFolder.getName();
//          toFile(readFileToString(temp), "Copy".concat(temp));
//      }
//  }

    public void getAllFilesInArrayList(final File fileOrFolder) {
        String temp = "";
        System.out.println("getAllFilesInArrayList fileOrFolder.getAbsolutePath()" + fileOrFolder.getAbsolutePath());
        if (fileOrFolder.isDirectory()) {
            for (final File fileEntry : fileOrFolder.listFiles()) {
                if (fileEntry.isFile()) {
                    temp = fileEntry.getAbsolutePath();
                    allFilesArrayList.add(temp);
                }
            }
        }
        if (fileOrFolder.isFile()) {
            temp = fileOrFolder.getAbsolutePath();
            allFilesArrayList.add(temp);
        }
        totalNumberOfFiles = allFilesArrayList.size();
        for (int i = 0; i < allFilesArrayList.size(); i++) {
            System.out.println("getAllFilesInArrayList path: " + allFilesArrayList.get(i));
        }
    }

    public synchronized String getNextFile() {
        nextFile++;
        if (nextFile < allFilesArrayList.size()) {
//          File tempFile = new File(allFilesArrayList.get(nextFile));
            return allFilesArrayList.get(nextFile);
        } else {
            return null;
        }
    }

    @Override
    public void run() {
        getAllFilesInArrayList(file);
        executorService = Executors.newFixedThreadPool(allFilesArrayList.size());
        while(nextFile < totalNumberOfFiles)
        {
            String tempGetFile = getNextFile();
            File tempFile = new File(allFilesArrayList.get(nextFile));
            toFile(readFileToString(tempFile.getAbsolutePath()), "Copy".concat(tempFile.getName()));
        }
    }

    public static void main(String[] args) {
        Test6 test6 = new Test6(new File("C:/Users/Nomi/Desktop/Workspace2/Test6/Test Files/"));
        Thread thread = new Thread(test6);
        thread.start();
//      executorService.execute(test6);
//      test6.listFilesForFolder(new File("C:/Users/Nomi/Desktop/Workspace2/Test6/"));
    }
}

The programs’ doing what’s expected. It goes into the folder, grabs a file, reads it into a string and then writes the contents to a new file.
I would like to do this multi threaded. If the folder has N number of files, I need N number of threads. Also I would like to use executor framework if possible. I’m thinking that there can be a method along this line:

public synchronized void getAllFilesInArrayList() {
        return nextFile;
    }

So each new thread could pick the next file.
Thank you for your help.

Error:

Exception in thread "Thread-0" java.lang.IllegalArgumentException
    at java.util.concurrent.ThreadPoolExecutor.<init>(ThreadPoolExecutor.java:589)
    at java.util.concurrent.ThreadPoolExecutor.<init>(ThreadPoolExecutor.java:480)
    at java.util.concurrent.Executors.newFixedThreadPool(Executors.java:59)
    at Test6.run(Test6.java:112)
    at java.lang.Thread.run(Thread.java:662)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T05:01:14+00:00Added an answer on June 16, 2026 at 5:01 am

    Firstly, your approach to the problem will result in more synchronization and race condition worries than seems necessary. A simple strategy to keep your threads from racing would be this:

    1) Have a dispatcher thread read all the file names in your directory.

    2) For each file, have the dispatcher thread spawn a worker thread and hand off the file reference

    3) Have the worker thread process the file

    4) Make sure you have some sane naming convention for your output file names so that you don’t get threads overwriting each other.

    As for using an executor, a ThreadPoolExecutor would probably work well. Go take a look at the javadoc: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ExplicitChannelRead { /** * @param args
import java.nio.charset.Charsets in my class UriCodec.java,but when i use javac(jdk6) compile this class error.
import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; public class Main implements Runnable { private final CountDownLatch cdl1
I am using bufferedWriter to write to a file like this import java.io.BufferedWriter; import
i have this code to download a single file . import java.io.FileOutputStream; import java.io.IOException;
import java.util.Scanner; public class CourseSplitter { public static void main(String args[]){ Scanner keyboard =
import java.util.Collection; import example.Event; public interface Query { public boolean hasMore (); public Collection<Event>
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateDemo { public static void main(String[]
import java.io.*; import java.util.Scanner; import java.util.StringTokenizer; public class Filereader { public static void main(String[]
import java.util.Scanner; public class smth { Scanner input = new Scanner(System.in); int array[]={}; }

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.