Class createfileutil {public static string createtempfile (string prefix, string suffix, string dirname) {file tempfile = NULL; If (dirname = NULL) {try {// create temporary file tempfile = file in the default folder. createtempfile (prefix, suffix); // return the temporary file path return tempfile. getCanonicalPath ();} catch (ioexception e) {e. printstacktrace (); system. out. println ("creating temporary file failed! "+ E. getmessage (); return NULL ;}} else {file dir = new file (dirname); // If the directory of the temporary file does not exist, create if (! Dir. exists () {If (! Createfileutil. createdir (dirname) {system. Out. println ("Creating a temporary file failed. The directory where the temporary file cannot be created! "); Return NULL ;}}try {// create temporary file tempfile = file in the specified directory. createtempfile (prefix, suffix, DIR); return tempfile. getCanonicalPath ();} catch (ioexception e) {e. printstacktrace (); system. out. println ("creating temporary file failed! "+ E. getmessage (); return NULL ;}} public static Boolean createdir (string destdirname) {file dir = new file (destdirname); If (dir. exists () {return false;} If (! Destdirname. endswith (file. separator) {destdirname = destdirname + file. separator;} // create the directory if (dir. mkdirs () {return true;} else {return false;} public static Boolean createfile (string destfilename) {file = new file (destfilename); If (file. exists () {return false;} If (destfilename. endswith (file. separator) {return false;} // determines whether the directory of the target file exists if (! File. getparentfile (). exists () {// If the directory of the target file does not exist, create the parent directory if (! File. getparentfile (). mkdirs () {return false ;}// create the target file try {If (file. createnewfile () {return true;} else {return false;} catch (ioexception e) {e. printstacktrace (); system. out. println ("Creating a single file" + destfilename + "failed! "+ E. getmessage (); Return false ;}}}
Class redirect {// redirect the print to a file public static void start (string filename) {createfileutil. createfile (filename); file = new file (filename); try {system. setout (New printstream (New fileoutputstream (file, true);} catch (filenotfoundexception e) {e. printstacktrace ();}}}
Common Tools-createfileutil, redirect