-1

My teacher wants me to create a Course list of Instructor and Textbook, and I don't know how to put all the course names into a file.

Here is my code:

public static void main(String[] args) {

    Instructor instruct = new Instructor();
    TextBook text = new TextBook();
    String course = instruct.instructor() + ", " + text.textbook();
    System.out.println(course);
    int i = 0;
    ArrayList<String> courseList = new ArrayList<String>(i);
    while (true) {
        courseList.add(course);

    }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Always [search Stack Overflow](https://duckduckgo.com/?q=site%3Astackoverflow.com+write+arraylist+to+file+java&t=osx&ia=web) thoroughly before posting. – Basil Bourque Mar 04 '22 at 05:58

1 Answers1

1

To write your string inside a .txt file, the simplest method would be Java's FileWriter Class. You can use the following code snippet to try and write your string to the file.

import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

  public static void add(String text) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write(text);
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
  
Marc
  • 11
  • 2