-2
如何使用线程写入文件?每个文件应该是100行,每行长度为100个字符。这项工作必须执行线程和I \ O。如何使用线程写入文件?
我的代码:
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!");
}
}
}
我的代码是正确的?我需要用100行和100个字符创建文件。字符必须取决于文件名。如果我创建一个名为1的文件,并且填充名称必须是1.谢谢。
你有什么问题吗?如果你只是想知道它是否工作...然后测试它。 –