I have problem. I need to create 9 files, each called from thread name. Each file will be called 1.txt, 2.txt, 3.txt etc. Each file will be filled with a symbol that corresponds to the name of the file (1.txt file is "1"). Each file should be 100 lines, each line length is 100 characters. This work must perform threads of execution and I\O. I need to read the contents of these files in the resulting file super.txt, when using several threads.
My code:
public class CustomThread extends Thread {
Thread t;
String threadName;
CustomThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
if (t == null) {
t = new Thread(this);
}
add(threadName);
}
public 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 main:
public class Main {
public static void main(String[] args) {
CustomThread T1 = new CustomThread("1");
T1.start();
CustomThread T2 = new CustomThread("2");
T2.start();
}
}
First question. I need, to make threads in cycle. Look on my main: I create
CustomThread T1 = new CustomThread("1");
T1.start();
But, i want to create 9 files in cycle. How to do this ?
Second question. I need to write in every my file from multiple threads.
Third question. How to write from multiple threads in result file five contents of thats files ?