在Java中,我需要将字符串写入一个新文件,例如 'c:\test\upload\myfile.txt',如果'upload'文件夹不存在,则会自动创建。如何实现?Apache Commons IO有这个API吗?
File file = new File(...);
file.mkdirs(); //for several levels, without the "s" for one level
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("...");
创建此抽象路径名命名的目录,包括所有必要但不存在的父目录。请注意,如果此操作失败,它可能已成功创建了某些必要的父目录。
返回值: 如果目录以及所有必要的父目录被创建,则返回true;否则返回false。
除了被采纳的答案外,由于该问题还提到了库 Apache Common IO,因此我在以下内容中提供使用这个好用库的解决方案:
File file = new File("... the directory path ...");
FileUtils.forceMkdir(file);
FileUtils
类,位于 org.apache.commons.io
包中,并使用了方法 forceMkdir
,其功能是“创建一个目录,包括必要但不存在的父目录”。请注意,html标签已被保留。IOException
异常)。 - naXa stands with Ukrainenew File(fileToSave.getParent()).mkdirs();