当父文件夹不存在时,怎么用..mkdirs()创建父目录,将数据写入.txt文件并读出

大家好,我是被白菜拱的猪。

人在室中做,事从天上来。嘀嘀嘀嘀,qq头像在右下角闪烁了起来 倪皓帅 能不能帮我。好小子,布置给你的任务你不好好做,你让我来,行,看在你叫我皓帅哥的份上,我就帮你一下。

在这里插入图片描述

首先将学生封装一个类,然学生信息方法哦list里面,然后从list里面存到.txt里。

public class Student {
	private String grade;
	private String classId;
	private int code;
	private String name;
	private String sex;

看到这个这个功能的第一想法就是把2019级放一个文件夹然后里面又有班级的文件夹,最后113.txt里面包含学生信息
最大的问题就是当父目录不存在时怎么创建.txt文件。FileOutStream是当父目录存在,.txt不存在可以创建.txt。
我的解决办法是

	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. 先获取父目录

File fileParent = file.getParentFile();

2.判断父目录是否已经存在

if (!fileParent.exists()) {

3.如果不存在用.mkdirs()创建父目录

fileParent.mkdirs(); }

4.最后用creatNewFile()创建.txt文件

file.createNewFile();

假如对怎么将数据取出,这里有详细代码https://download.csdn.net/download/weixin_44226263/11467503

of course,学长很满意…

发布了24 篇原创文章 · 获赞 4 · 访问量 2038

猜你喜欢

转载自blog.csdn.net/weixin_44226263/article/details/98336021