1

I want to be able to print the output of this method in an output file how can I do that? here is the method that I want to print

        System.out.println("Student List ");
        for (int i = 0; i < this.myStudents.size();i++){
            System.out.println((i+1)+"."+
                    this.myStudents.get(i).getName()+" ->ID= "+
                    this.myStudents.get(i).getIDNumber()+" ->GPA:"+
                    this.myStudents.get(i).getGPA());
        }
    }
sally
  • 13
  • 5

2 Answers2

2
  FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);

    for (int i = 0; i < this.myStudents.size();i++){
            printWriter.print((i+1)+"."+
                this.myStudents.get(i).getName()+" ->ID= "+
                this.myStudents.get(i).getIDNumber()+" ->GPA:"+
                this.myStudents.get(i).getGPA());
    }


    printWriter.close();
dyrod
  • 56
  • 4
1

*All the code I present here is taken from https://www.w3schools.com/java/java_files_create.asp I highly recommend checking it for more details.

First, you would need to create a file/ check if one exists,

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

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

After that you should be able to write in the file using the FileWriter class

FileWriter myWriter = new FileWriter("filename.txt");

and to write in a file you want to use the .write method

 myWriter.write("a string");

and once you are done modifying the file using the close() method to close the file

myWriter.close();
Ido
  • 89
  • 11