Issue
I'm writing a string file from disk using PrintWriter
with this code:
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();
}
}
}
The problem is that if the path contains a directory then PrintWriter throws an exception. How can I tell PrintWriter to create missing folders of its path?
Solution
Use the PrintWriter
constructor that takes a File
:
PrintWriter(File file)
and the file might be created using the following code:
File fullPath = new File(path);
File directory = new File(fullPath.getParent());
directory.mkdirs();
File file = new File(directory, fullPath.getName());
Answered By - Adam Siemion