0

Je rencontre des problèmes lors de la création d'un constructeur de thread qui acceptera un nom de fichier et un tableau de données 2-D à écrire dans le fichier. La méthode thread run est supposée écrire ce tableau 2-d dans le fichier, puis instancier ce thread pour le fichier courses.txt et le fichier students.txt. J'essaye de faire ceci en employant l'application multithreaded. Le tableau 2D sera un tableau de chaînes 2D, comme je l'ai déjà créé sur le code. J'ai hard-code les données dans le tableau 2D String mais je suis un peu confus quant à la façon dont je vais passer ce tableau et nom de fichier à un thread qui va écrire le fichier. Je sais que je peux écrire une classe de thread avec une méthode run() qui écrira un fichier. Comment puis-je créer deux instances de ce thread dans le fichier main() dans WriteFiles.java, puis passer une des données de l'étudiant et passer l'autre les données du cours?ayant des problèmes lors de la création d'un WriteFiles avec une application multithread

C'est le code que j'ai jusqu'à présent et adorerait quelques conseils:

import java.util.*; 
import java.io.*; 

class WriteFiles implements Runnable 
{ 

    static final String FILE = "courses.txt"; 
    static final String FILE2 = "students.txt"; 
    BufferedWriter bw; 
    Thread thread[] = new Thread[2]; 
    private String studentList[][]; 
    private String courseList[][]; 


    public WriteFiles() 
    { 
    try 
    { 
     bw = new BufferedWriter(new FileWriter(FILE)); 
     bw = new BufferedWriter(new FileWriter(FILE2)); 
    } 
    catch(FileNotFoundException fnfe) 
    { 
     System.out.println(fnfe); 
     System.exit(1); 
    } 
    catch(IOException ioe) 
    { 
     System.out.println(ioe); 
     System.exit(2); 
    } 

    } 


    public void writeFile(String str) 
    { 

    try{ 
     bw.write(str); 
    } catch(IOException ioe){ 
     System.out.println(ioe); 
    } 
    } 



    public void run() 
    { 

     String studentList[][] = { 
      {"Python","INSY 3300","530-650 MW","1,3"}, 
      {"Networking","INSY 3303","530-650 TR","1,3"}, 
      {"DBMS","INSY 3304","900-950 MWF","1,3"}, 
      {"Analysis&Design","INSY 3305","700-820 TR","1,3"}, 
      {"Java I","INSY 4305","700-820 TR","1,3"}, 
      {"Java II","INSY 4306","530-650 TR","1,3"}, 
      {"Mobile App","INSY 4308","200-320 TR","1,3"}, 
      {"Web Development","INSY 4315","1000-1050 MWF","1,3"}, 
      {"Resource Management","INSY 4325","100-220 TR","1,3"} 
           }; 

     String courseList[][] = { 
      {"US","NONRESIDENT","123456","Jones","123 Cooper St","Arlington","Texas","76019","12345"}, 
      {"INT","ACTIVE","A-654789","Degrassey","18 Love Lane","Dallas","Texas","75052","67123"}, 
      {"INT","INACTIVE","A-543891","Franco","1201 Trail Road","Euless","Texas","74032","19814"}, 
      {"US","RESIDENT","345123","Hughes","1803 Division","Fort Worth","Texas","76034","674532"}, 
      {"US","RESIDENT","988776","Cooper","111 Marsh Lane","Bedford","Texas","76111","90906"}, 
      {"INT","INACTIVE","B-577463","Patel","2218 Border St","Arlington","Texas","76015","81832"} 
           }; 



    } 

    public void writeCourses() 
    { 
for (Student s:studentList){ 

      System.out.print(s.toString()); 
     } 
    } 

    public void writeStudents() 
    { 
     for (Course c:courseList){ 

      System.out.print(c.toString()); 
     } 

    } 


    public static void main(String arg[]) 
    { 
    WriteFiles myTread = new WriteFiles(); 
    myTread.writeCourses(); 
    myTread.writeStudents(); 
    } 
} 

La sortie students.txt finale est censé ressembler à ceci avec un; divisé par les données:

Etats-Unis, non-résidents, 123456, Jones, 123, rue Cooper, Arlington, Texas, 76019, 12345 INT, ACTIVE, A-654789, Degrassey, 18 Love Lane, Dallas, Texas, 75052, 67123 INT, INACTIF; A-543891; Franco; 1201 Trail Road; Euless; Texas; 74032; 19814 US; RÉSIDENT; 345123; Hughes; 1803 Division; Fort Worth; Texas; 76034; 674532 ; RÉSIDENT; 988776; Cooper; 111 Lane Marsh, Bedford, Texas, 76111, 90906 INT; INACTIF; B-577463, Patel, 2218 Border St, Arlington, Texas, 76015, 81832

La sortie course.txt finale est censé ressembler à ceci avec une ; divisé par les données:

python; INSY 3300; 530-650 MW; 1; 3 Networking; INSY 3303; 530-650 TR; 1; 3 SGBD; INSY 3304; 900-950 MWF; 1; 3 Analyse et conception; INSY 3305; 700-820 TR; 1; 3 Java I; INSY 4305; 700-820 TR; 1; 3 Java II; INSY 4306; 530-650 TR; 1; 3 Mobile App; INSY 4308; 200-320 TR; 1; 3 développement Web; INSY 4315; 1000-1050 MWF; 1; la gestion des ressources 3 ; INSY 4325; 100-220 TR; 1; 3

J'ai eu aucun problème pour que cela fonctionne une méthode différente et a réussi, mais j'essaie maintenant une approche différente en utilisant une application multithread. Il y avait là une sortie de travail sans fils:

import java.util.*; 
import java.io.*; 

public class WriteFiles { 
    private static Formatter output; 
    private static Scanner input; 

    public static void main(String[] args) { 

     ArrayList<Student> studentList = new ArrayList<Student>(); 
     writeTextFile1(); 

     for (Student s:studentList){ 

      System.out.print(s.toString()); 
     } 
     ArrayList<Course> courseList = new ArrayList<Course>(); 
     writeTextFile(); 

     for (Course c:courseList){ 

      System.out.print(c.toString()); 
     } 
    } 

    public static void writeTextFile(){ 
     try{ 
      output = new Formatter("courses.txt"); 
      output.format("%s;%s;%s;%d;%d%n","Python","INSY 3300","530-650 MW",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Networking","INSY 3303","530-650 TR",1,3); 
      output.format("%s;%s;%s;%d;%d%n","DBMS","INSY 3304","900-950 MWF",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Analysis&Design","INSY 3305","700-820 TR",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Java I","INSY 4305","700-820 TR",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Java II","INSY 4306","530-650 TR",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Mobile App","INSY 4308","200-320 TR",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Web Development","INSY 4315","1000-1050 MWF",1,3); 
      output.format("%s;%s;%s;%d;%d%n","Resource Management","INSY 4325","100-220 TR",1,3); 
      output.close(); 
     } 
     catch(IOException ioe){ 
     ioe.printStackTrace(); 
     } 
    } 

    public static void writeTextFile1(){ 

     try{ 
      output = new Formatter("students.txt"); 
      output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","US","NONRESIDENT","123456","Jones","123 Cooper St","Arlington","Texas",76019,12345); 
      output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","INT","ACTIVE","A-654789","Degrassey","18 Love Lane","Dallas","Texas",75052,67123); 
      output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","INT","INACTIVE","A-543891","Franco","1201 Trail Road","Euless","Texas",74032,19814); 
      output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","US","RESIDENT","345123","Hughes","1803 Division","Fort Worth","Texas",76034,674532); 
      output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","US","RESIDENT","988776","Cooper","111 Marsh Lane","Bedford","Texas",76111,90906); 
      output.format("%s;%s;%s;%s;%s;%s;%s;%d;%d%n","INT","INACTIVE","B-577463","Patel","2218 Border St","Arlington","Texas",76015,81832); 
      output.close(); 
     } 
     catch(IOException ioe){ 
     ioe.printStackTrace(); 
     } 
    } 
} 

Répondre

0

Je suis un peu confus quant à la façon dont je vais passer ce tableau et le nom à un fil qui va écrire le fichier

À moins que je Je ne comprends pas le problème, la réponse courte est avec des arguments au constructeur. Vous devez passer un String[][] pour le contenu et un String comme nom de fichier de sortie.

public class WriteFile implements Runnable { 
    private final String[][] contentLines; 
    private final String outputFilename; 
    public WriteFile(String[][] contentLines, String outputFilename) { 
     this.contentLines = contentLines; 
     this.outputFilename = outputFilename; 
    } 
    public void run() { 
     // write the content to the file-name 
     BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilename)); 
     try { 
     for (String[] contentLine : contentLines) { 
      ... 
     } 
     } finally { 
     bw.close(); 
     } 
    } 
} 

Vous appelleriez alors cela en disant quelque chose comme:

Thread studentThread = new Thread(new WriteFile(studentList, "students.txt")); 
studentThread.start(); 
Thread courseThread = new Thread(new WriteFile(courseList, "courses.txt")); 
courseThread.start(); 
// now wait for the threads to finish writing 
studentThread.join(); 
courseThread.join(); 

Si vous passez dans Student ou Course objets dans ce runnable alors vous devrez créer un autre runnable pour gérer chaque type de données en cours d'écriture.

// student file writer runnable 
Thread studentThread = new Thread(new WriteStudentFile(studentList, "students.txt")); 
// course file writer runnable 
Thread courseThread = new Thread(new WriteCourseFile(courseList, "courses.txt")); 
+0

cela aide l'homme. Mais maintenant on me dit que nous devons utiliser Formatter et ne pouvons pas utiliser BufferedWriter. J'insère le tableau String pour student dans la méthode try, correct? alors une autre méthode d'essai pour les cours? ..... et dans le principal c'est où je commence les discussions. – Donovan

+0

Le tableau de chaînes peut être pour l'un ou l'autre cours. La réutilisation de code est le bon point? Encore une fois, si vous devez les gérer différemment, il n'y a pas de point de partage de code. – Gray

+0

Aussi @Fred, je suppose que vous pouvez écrire le code 'Formatter' droit? – Gray

0

Je viens de découvrir que j'avais tout mon arraylist erroné. Je vais traiter tout cela comme une seule ligne, mais toujours un bc 2D sur mon programme GUI, je vais diviser le; termes

String studentList[][] = { 
     {"Python;INSY 3300;530-650 MW;1,3"}, 
     {"Networking;INSY 3303;530-650 TR;1,3"}, 
     {"DBMS;INSY 3304;900-950 MWF;1,3"}, 
     {"Analysis&Design;INSY 3305;700-820 TR;1,3"}, 
     {"Java I;INSY 4305","700-820 TR","1,3"}, 
     {"Java II","INSY 4306;530-650 TR;1,3"}, 
     {"Mobile App;INSY 4308;200-320 TR;1,3"}, 
     {"Web Development;INSY 4315;1000-1050 MWF;1,3"}, 
     {"Resource Management;INSY 4325;100-220 TR;1,3"} 
          }; 

    String courseList[][] = { 
     {"US;NONRESIDENT;23456;Jones;123 Cooper St;Arlington;Texas;76019;12345"}, 
     {"INT;ACTIVE;A-654789;Degrassey;18 Love Lane;Dallas;Texas;75052;67123"}, 
     {"INT;INACTIVE;A-543891;Franco;1201 Trail Road;Euless;Texas;74032;19814"}, 
     {"US;RESIDENT;345123;Hughes;1803 Division;Fort Worth;Texas;76034;674532"}, 
     {"US;RESIDENT;988776;Cooper;111 Marsh Lane;Bedford;Texas;76111;90906"}, 
     {"INT;INACTIVE;B-577463;Patel;2218 Border St;Arlington;Texas;76015;81832"} 
          }; 

Je suis encore un peu confus. Est-ce que j'écris le tableau de fils dans la main?

0

Résolu! Pour ceux qui voudraient se référer et s'ils rencontrent un tel problème, je partagerai le code:

//Donovan 
package hw2; 
//Importing Java imports that are required for the program to execute properly 
import java.util.concurrent.Executors; 
import java.util.concurrent.ExecutorService; 
import java.util.*; 
import java.io.*; 
//Creating my public & private class for WriteFiles that uses Runnable, including Formatter 
public class WriteFiles implements Runnable{ 
private String threadDonovan; 
private String[][] arrayDonovan; 
Formatter output; 
//Creating a WriteFiles which will accept a thread as a String and a 2D ArrayList for later Execution 
public WriteFiles(String str, String arrays[][]) 
{ 
//Create a string an array for later use in the run() 
threadDonovan = str; 
arrayDonovan = arrays; 
} 
//Time to run a try and catch methods 
public void run() 
    { 
     //First have to try a few things 
     try 
      { 
       //create a Formatter from my Thread 
       output = new Formatter(threadDonovan); 
       //Running 2 for loops to output the correct information into the .txt files 
       for (int i = 0; i < arrayDonovan.length; i++) 
        { 
         for (int j = 0; j < arrayDonovan[i].length; j++) 
          { 
           //Proper Formatting is Required so the .txt files 
           //are written properly so they're the same way as HW1 
           //and so the GUI doesn't run into any problems 
           output.format("%s%n",arrayDonovan[i][j]); 
          } 
        } 
       //Once the Data is written, have to close the Formatter     
       output.close();   
      } 
     //Now have to catch a few errors and print them to debug if needed 
     catch(IOException ioe) 
      { 
       ioe.printStackTrace(); 
       System.out.println(ioe); 
       System.exit(2); 
      } 
} 
//creating the main which will have the 2D ArrayList and the Executor Service 
public static void main(String[] args) throws InterruptedException 
    { 
    //create my 2D ArrayList for Students 
    String studentList[][] = { 
       {"US;NONRESIDENT;23456;Jones;123 Cooper St;Arlington;Texas;76019;12345"}, 
       {"INT;ACTIVE;A-654789;Degrassey;18 Love Lane;Dallas;Texas;75052;67123"}, 
       {"INT;INACTIVE;A-543891;Franco;1201 Trail Road;Euless;Texas;74032;19814"}, 
       {"US;RESIDENT;345123;Hughes;1803 Division;Fort Worth;Texas;76034;674532"}, 
       {"US;RESIDENT;988776;Cooper;111 Marsh Lane;Bedford;Texas;76111;90906"}, 
       {"INT;INACTIVE;B-577463;Patel;2218 Border St;Arlington;Texas;76015;81832"} 
           }; 
    //create my 2D ArrayList for Courses 
    String courseList[][] = { 
       {"Python;INSY 3300;530-650 MW;1;3"}, 
       {"Networking;INSY 3303;530-650 TR;1;3"}, 
       {"DBMS;INSY 3304;900-950 MWF;1;3"}, 
       {"Analysis&Design;INSY 3305;700-820 TR;1;3"}, 
       {"Java I;INSY 4305;700-820 TR;1;3"}, 
       {"Java II;INSY 4306;530-650 TR;1;3"}, 
       {"Mobile App;INSY 4308;200-320 TR;1;3"}, 
       {"Web Development;INSY 4315;1000-1050 MWF;1;3"}, 
       {"Resource Management;INSY 4325;100-220 TR;1;3"} 
          }; 
    //What will be created once ExecutorService Starts for Students 
    WriteFiles studentFile = new WriteFiles("students.txt",studentList); 
    //What will be created once ExecutorService Starts for Courses 
    WriteFiles courseFile = new WriteFiles("courses.txt",courseList); 
    //Begin the Executor Service 
    ExecutorService executorService = Executors.newCachedThreadPool(); 
    //start the first Task/Thread to create students.txt from the studentList 2D ArrayLIst   
    executorService.execute(studentFile); 
    //start the first Task/Thread to create courses.txt from the courseList 2D ArrayLIst 
    executorService.execute(courseFile); //start task 2 
    //End the Executor Service 
    executorService.shutdown(); 
    } 
}