Java core programming-File operations, javafile
1. Overview
Access to the File system is required for each language. java provides the File class to create, rename, delete, operate on the File list, and determine whether the File or directory exists.
2. Operations on files/Directories
The operations include:
1: Create an object.
2: determine whether it is a directory/file.
3: Determine whether a directory or file exists.
4. Modify the file name.
5: create a file/create a directory/create all directories.
6: Query all directories and file 8 output file paths in the directory
7. delete files/Directories
Note: not all operations must be performed once.
3. Related code
Public static void main (String [] args) {try {File file = new File ("D: \ test "); // create a directory object File txt = new File ("D: \ test \ tex.txt"); // create a File object System. out. println ("OK"); if (! File. isDirectory () {// determine whether the directory is if (! File. exists () {// checks whether a file exists in the directory. mkdir (); // create a directory file. mkdirs (); // create all directories System. out. println ("OK") ;}} if (! Txt. isFile () {// determine whether it is a file if (! Txt. exists () {// determine whether the File exists. File newName = new File ("D: \ test \ tex2.txt"); // create a File object txt. renameTo (newName); // rename the file txt. createNewFile (); // create a new file, which must handle io exception System. out. println ("OK") ;}} File path = new File ("D: \ data \ log_Tyj"); File [] files = path. listFiles (); // query the file list in the directory for (int I = 0; I <files. length; I ++) {System. out. println (files [I]. getAbsolutePath (); // output Object Path} file. delete (); // delete the directory. All directories and files under the directory will be deleted. txt. delete (); // delete file} catch (IOException e) {e. printStackTrace ();}}