使用 Java 在文件中打印 for 循环



我希望能够在输出文件中打印此方法的输出 我该怎么做?这是我想要打印的方法

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

*我在这里提供的所有代码都取自 https://www.w3schools.com/java/java_files_create.asp 我强烈建议您检查一下以获取更多详细信息。

首先,您需要创建一个文件/检查是否存在,

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

之后,您应该能够使用 FileWriter 类写入文件

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

并写入要使用 .write 方法

的文件
myWriter.write("a string");

一旦你完成了使用close((方法修改文件以关闭文件

myWriter.close();

最新更新