如何用线程写入文件?
How to write in a file with threads?
如何用线程写入文件?每个文件应为 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 个字符的文件。 Сcharacter 必须取决于文件名。如果我创建一个名为1的文件,填充的名称必须是1。谢谢。
根据您的要求,您的代码看起来是正确的,即编写 100 行并且每行包含 100 个字符。假设是,线程的名称将是单个字符,因为您正在将 threadName
写入文件。我有 一些结束建议 来完成您的实施。他们自己测试。如果您发现任何问题,请发表评论。
- 要让每行 100 个字符,您需要将
new line
个字符语句移动到外循环。
- 将所有数据写入文件后,对文件进行
flush()
和close()
保存。
- 您正在使用
threadName
创建文件,您可能想要添加要创建的文件的起始路径位置。
- 显然您缺少
main()
方法。创建 class 和 start()
线程的对象。
- 您不需要创建单独的
Thread
实例,run()
方法将在单独的线程中执行,因为您正在扩展 Thread
class。
如何用线程写入文件?每个文件应为 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 个字符的文件。 Сcharacter 必须取决于文件名。如果我创建一个名为1的文件,填充的名称必须是1。谢谢。
根据您的要求,您的代码看起来是正确的,即编写 100 行并且每行包含 100 个字符。假设是,线程的名称将是单个字符,因为您正在将 threadName
写入文件。我有 一些结束建议 来完成您的实施。他们自己测试。如果您发现任何问题,请发表评论。
- 要让每行 100 个字符,您需要将
new line
个字符语句移动到外循环。 - 将所有数据写入文件后,对文件进行
flush()
和close()
保存。 - 您正在使用
threadName
创建文件,您可能想要添加要创建的文件的起始路径位置。 - 显然您缺少
main()
方法。创建 class 和start()
线程的对象。 - 您不需要创建单独的
Thread
实例,run()
方法将在单独的线程中执行,因为您正在扩展Thread
class。