在把数据写出去到文件的时候,可能会遇到所给的目录不存在,那么就会抛异常。“”系统找不到指定的路径“”。因为所目录不在,所以就异常 ,
那么怎么让他判断下,要是文件目录不存在了,就新建目录,然后再继续,就可以正确执行了。
下面示范如何操作。有姿势不对的地方,还请各位指出来,我好修正,以免误人子弟。
先看bug图:
这个是在,所操作的目录不存在的时候,直接写文件,就失败了。
下面看代码吧。
/**
* 一个目录要是不存在,则创建目录,然后写文件。
*/
private static void testFileIsExists() {
String path = "D:/lxk/conf/es-source.properties";
File file = new File(path);
System.out.println(file.getParentFile());
if (!file.getParentFile().exists()) {
boolean result = file.getParentFile().mkdirs();
if (!result) {
System.out.println("创建失败");
}
}
Properties properties = new Properties();
properties.setProperty("sss", "ssa");
properties.setProperty("ssasds", "ssaas");
OutputStreamWriter outputStreamWriter = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(path, false);//true表示追加打开,false每次都是清空再重写
outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
properties.store(outputStreamWriter, "");
} catch (Exception e) {
System.out.println("writeOrderedPropertiesFile IOException:" + e.getMessage());
} finally {
if (outputStreamWriter != null) {
try {
outputStreamWriter.close();
} catch (IOException e) {
System.out.println("writeOrderedPropertiesFile close IOException:" + e.getMessage());
}
}
}
}
这下子,代码直接运行就是OK的了。也没有引用其他特别的jar包,全是jdk里面的包。然后运行完之后,就会生成对应的目录以及文件。
代码中,我给出的是导出文件的全路径,包含了文件名。
file.getParentFile() 这个方法就是得到文件所在的目录,
mkdirs() 就是直接创建目录目录。即使是多层也没关系。
这个视情况而定,要是你的就只是目录的话,就不用这么干了,重点是先创建目录,目录存在了,那么就好继续创建文件了。
最后,就有如下结果:
目录和文件都有啦。
先不要在意这个问题的简单,我就简单的留个笔记吧。
觉得此文有用的,不嫌麻烦的,就点个赞吧,要是嫌弃麻烦呢,也麻烦点个赞嘛,要是实在不想点赞呢,也不是不可以。
但是,你要是想踩一脚呢,那还是赶紧,马上,快快的闪人。
小心我手里三十米长的大刀。哼哼。想想都怕 !!!