'How can I write an ArrayList into a File [duplicate]
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);
}
}
Solution 1:[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();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marc |
