-
Creating a new file...
Does anyone know how to create a file in a directory where the directory has not yet been created?
i.e. dir1/dir2/dir3/myFile.txt (where dir1, dir2 and dir3 are created if they don't already exist).
I wrote this little app for testing:
Code:
import java.io.*;
public class Writing {
public static void main(String[] args) throws IOException {
File target = new File(args[0]);
if (!target.exists()) {
boolean success = target.createNewFile();
System.out.println("Attempted to create new file..." + success);
}
PrintStream ps = new PrintStream(new FileOutputStream(target));
ps.println("Hello");
}
}
-
One step better...
Not quite automatic, but closer...
Code:
import java.io.*;
public class Writing {
public static void main(String[] args) throws IOException {
File dir = new File(args[0]);
File file = new File(dir, args[1]);
boolean success;
success = dir.mkdirs();
System.out.println("Attempted to create dirs..." + success);
success = file.createNewFile();
System.out.println("Attempted to create new file..." + success);
PrintStream ps = new PrintStream(new FileOutputStream(file));
ps.println("Hello");
}
}