Example one: Creating a file
PackageJava file class;ImportJava.io.File;Importjava.io.IOException; Public classAASD { Public Static voidMain (string[] args) {//File.separator represents a delimiter//D:\\lampFile file1 =NewFile ("D:" +file.separator+ "Lamp.txt"); if(!file1.exists ()) { Try { Booleanb=File1.createnewfile (); System.out.println ("Create File:" +b); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
Example two: Creating a Directory
PackageJava file class;ImportJava.io.File;Importjava.io.IOException; Public classAASD { Public Static voidMain (string[] args) {//File.separator represents a delimiter//D:\\lampFile file1 =NewFile ("D:" +file.separator+ "lamp"); if(!file1.exists ()) { Booleanb=File1.mkdir (); System.out.println ("Create directory:" +b); } }}
The key technical points for creating files and directories are as follows:
1. The createnewfile of the file class creates a new empty file based on the abstract path, and the creation fails when the abstract path-developed file exists.
2. The mkdir method of the file class creates a directory based on an abstract path
3. The Mkdirs method of the file class creates a directory based on an abstract path, including creating a required but nonexistent parent directory
4, the File class Createtempfile method creates the temporary file, may develop the temporary file filename prefix, the suffix and the file directory, if does not specify the directory, then holds in the system's temporary folder.
5, in addition to the Mkdirs method, the above method when creating files and directories, must ensure that the target file does not exist, and the parent directory exists, otherwise it will create a failure
Java_ File class