Hello everyone, I am a pig arched by cabbage.
People do things in the room, things come from heaven. Dididididi, qq head flashed in the lower right corner Ni Haoshuai can help me. Good boy, you can't do well the tasks assigned to you, you let me come, okay, for the sake of calling me handsome boy, I will help you.
First encapsulate a class for the students, then the student information method is in the list, and then save it from the list to .txt.
public class Student {
private String grade;
private String classId;
private int code;
private String name;
private String sex;
The first idea to see this function is to put the 2019 level in a folder and then the class folder. Finally, the
biggest problem in 113.txt contains student information is how to create a .txt file when the parent directory does not exist. FileOutStream is to create a .txt when the parent directory exists and .txt does not exist.
My solution is
public void wirteData() {
StudentManager sm = new StudentManager();
List<Student> slist = sm.add();
FileOutputStream fos = null;
File file = null;
try {
for (Student stu : slist) {
file = new File("E:/stu/" + stu.getGrade() + "/" + stu.getClassId() + ".txt");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
file.createNewFile();
fos = new FileOutputStream(file, true);
String stu1 = stu.getCode() + "\t" + stu.getName() + "\t" + stu.getSex() + "\n";
fos.write(stu1.getBytes());
System.out.println("添加成功");
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
file = new File(“E:/stu/” + stu.getGrade() + “/” + stu.getClassId() + “.txt”);
1. Get the parent directory first
File fileParent = file.getParentFile();
2. Determine whether the parent directory already exists
if (!fileParent.exists()) {
3. If it does not exist, use .mkdirs () to create the parent directory
fileParent.mkdirs(); }
4. Finally, use creatNewFile () to create a .txt file
file.createNewFile();
If you want to get the data out, here is the detailed code https://download.csdn.net/download/weixin_44226263/11467503
Of course, the seniors are very satisfied ...