2015-09-12 60 views
-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.谢谢。

+2

你有什么问题吗?如果你只是想知道它是否工作...然后测试它。 –

回答

1

根据您的要求,您的代码看起来是正确的,即写100行,每行包含100个字符。假设是,线程的名称将是单个字符,因为您正在将threadName写入该文件。我有几个结束建议来完成您的实施。他们自己测试它。如果您发现任何问题,请发表评论。

  1. 要让每行有100个字符,您需要将new line个字符语句移动到外部循环。
  2. 一旦你的整理写入所有的数据文件,做flush()close()文件,为了保存它。
  3. 您正在使用threadName创建文件,您可能想要为要创建的文件添加起始路径位置。
  4. 显然你错过了main()方法。创建类的对象和start()的线程。
  5. 您无需创建单独的Thread实例,run()方法将在单独的线程中执行,因为您正在扩展Thread类。