【问题标题】:How to create missing folders from path with PrintWriter?如何使用 PrintWriter 从路径创建丢失的文件夹?
【发布时间】:2019-03-20 06:31:12
【问题描述】:

我正在使用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 创建其路径的缺失文件夹?

【问题讨论】:

    标签: java eclipse outputstream fileoutputstream printwriter


    【解决方案1】:

    使用采用FilePrintWriter 构造函数:

    PrintWriter(File file)
    

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

    File fullPath = new File(path);
    File directory = new File(fullPath.getParent());
    directory.mkdirs();
    File file = new File(directory, fullPath.getName());
    

    【讨论】:

    • @NullPointerException 我已经更新了答案。现在它使用path。如果目录已经存在,那不是问题。
    • 应该先存在()吗?
    【解决方案2】:
    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();
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-15
      • 1970-01-01
      • 2014-03-08
      • 2019-05-17
      • 1970-01-01
      • 2010-10-14
      • 2012-03-16
      • 2015-11-14
      • 2019-09-07
      相关资源
      最近更新 更多