在写入新文件时自动创建整个路径 [英] Create whole path automatically when writing to a new file

查看:90
本文介绍了在写入新文件时自动创建整个路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 FileWriter的 。我使用这样:

I want to write a new file with the FileWriter. I use it like this:

FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt");

现在 dir1 dir2 目前不存在。我希望Java自动创建它们,如果它们还没有。实际上,Java应该设置整个文件路径(如果尚未存在)。

Now dir1 and dir2 currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.

我该如何实现?

推荐答案

如下:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

这篇关于在写入新文件时自动创建整个路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆