0

I'm having some issues trying to create a thread constructor that will accept a file name and a 2-d array of data to be written to the file. The thread run method is suppose to write that 2-d array to the file and then instantiate this thread for the courses.txt file and the students.txt file. I'm trying to do this by using multithreaded application. The 2D array will be a 2D String array, as I already created on the code. I've hard-code the data into the 2D String array but I am a bit confused as to how I'll pass that array and filename to a thread that will write the file. I know I can write one thread class with one run() method that will write either file. How do I create two instances of that thread in the main() in WriteFiles.java and then pass one the Student data and pass the other the Course data?

This is the code I have so far and would love some guidance:

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();
  }
}

The final students.txt output is suppose to look like this with a ; split per data:

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

The final course.txt output is suppose to look like this with a ; split per data:

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

I had no problem getting this to work a different method and was successful, but I am now trying a different approach using a multithreaded application. Here was a working output without threads:

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();
        }
    }
}

3 Answers3

0

I am a bit confused as to how I'll pass that array and filename to a thread that will write the file

Unless I'm not understanding the problem, the short answer is with arguments to the constructor. You would pass in a String[][] for the contents and a String as the output filename.

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();
      }
   }
}

You would then call this by saying something like:

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();

If you are passing in Student or Course objects into this runnable then you will need to create a different runnable for handling each type of data being written.

// 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"));
Gray
  • 115,027
  • 24
  • 293
  • 354
  • this helps man. But now I am being told that we have to use Formatter and cannot use BufferedWriter. I'm inserting the actual String array for student in the try method, correct? then another try method for courses? .....and in the main thats where I start the threads?. – Donovan Mar 06 '17 at 23:49
  • The string array can be for either student _or_ courses. Code reuse is the point right? Again, if you have to handle them differently then there's not point in sharing code. – Gray Mar 07 '17 at 01:18
  • Also @Fred, I assume you can writhe the `Formatter` code right? – Gray Mar 07 '17 at 01:18
  • I solved the correct way using Formatter and Executor Service. I posted the code above – Donovan Mar 08 '17 at 06:47
  • That's great. Please accept my answer if it was helpful. This isn't about the final solution @Donovan. – Gray Mar 08 '17 at 14:19
0

I just found out I had my arraylist all wrong. I'm going to treat it all as one single line but still a 2D bc on my GUI program I am going to split the ; terms

    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"}
                             };

I'm still a little confused. Am I writing the thread array in the main?

0

Solved it! For those that would want to reference and if they so happen to run into such similar problem, I'll be sharing the 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();
    }
}