-2

How to write in a file with threads ? Each file should be 100 lines, each line length is 100 characters. This work must perform threads and I\O.

My code:

public class CustomThread extends Thread{
        private Thread t;
        private String threadName;

    CustomThread(String threadName){
        this.threadName = threadName;
    }

public void run () {
 if (t == null)
      {
         t = new Thread (this);
      }
         add(threadName);
}

public synchronized void add(String threadName){

        File f = new File(threadName + ".txt");

        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("File does not exists!");
            }
        }

        FileWriter fw = null;
        try {
        fw = new FileWriter(f);
        for (int i = 0; i < 100; i++) {
            for (int j = 0; j < 100; j++) {
                fw.write(threadName);
                fw.write('\n');
            }

        }

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("File does not exists!");
        } 
        }
}

My code is correct ? I need to create file with 100 lines and 100 characters. Сharacter must depend on the file name. If I create a file named 1, and the name of the filling must be 1. Thanks.

Valeriu
  • 171
  • 1
  • 1
  • 11

1 Answers1

1

Your code looks correct as per your requirement which is writing 100 lines and each line containing 100 characters. The assumption is, name of the thread will be single character, because your are writing threadName to the file. I have few closing suggestion to complete your implementation. They test it by yourself. If your find any issue, do comment.

  1. To have each line 100 characters, you need to move new line characters statement to outer loop.
  2. Once your finishing writing writing all the data to file, do flush() and close() the file, for saving it.
  3. You are creating the file with threadName, You might want to add the starting path location for the file to be created.
  4. Obviously you are missing main() method. Create object of the class and start() the thread.
  5. You don't need to create a separate Thread instance, The run() method will be executed in a separate thread because you are extending Thread class.
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73