如何使用 PrintWriter 从路径创建丢失的文件夹?

How to create missing folders from path with PrintWriter?

我正在使用 PrintWriter 从磁盘写入一个字符串文件,代码如下:

public static void storeString(String string, String path) {
    PrintWriter out = null;
    try {
        out = new PrintWriter(path, "UTF-8");       
        out.println(string);
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

问题是,如果路径包含目录,则 PrintWriter 会抛出异常。我如何告诉 PrintWriter 创建其路径中丢失的文件夹?

使用带有 File:

PrintWriter 构造函数
PrintWriter(File file)

并且可以使用以下代码创建文件:

File fullPath = new File(path);
File directory = new File(fullPath.getParent());
directory.mkdirs();
File file = new File(directory, fullPath.getName());
public class Main {
    public static void main(String[] args) {
        storeString("salam", "/yourPath/someUncreatedDir/yourfile.txt");
    }

    public static void storeString(String string, String path) {
        PrintWriter out = null;
        try {
            File dir = new File((new File(path)).getParent());
            dir.mkdirs();
            out = new PrintWriter(path, "UTF-8");
            out.println(string);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}