Create and delete files and folders in the java file operation.
This article describes the basic operations of java files, this includes creating files and folders in java, deleting files in java, obtaining all files in a specified directory in java, determining whether a specified path is a directory in java, and searching for all content in a specified directory in java. See the following example.
Create a file
Two constants of File (File. separator, File. pathSeparator ). In windows, you can use \ to separate them. But in linux, It is not. Therefore, if we want to make our code more robust across platforms, we should adopt these two constants.
Public static void createFileT () {File file = new File ("D:" + File. separator + "IO" + File. separator + "file01.txt"); // File file = new File ("D: \ IO \ file01.txt"); you can use try {file in Windows. createNewFile ();} catch (IOException e) {System. out. println ("IO exception"); e. printStackTrace ();}}
Delete an object
Public static void delectFile () {File file = new File ("D:" + File. separator + "IO" + File. separator + "file01.txt"); if (file. exists () {file. delete ();} else {System. out. println ("file does not exist ");}}
Create a folder
public static void createFileMix(){ File file=new File("D:"+File.separator+"IO" +File.separator+"file01"); file.mkdir(); }
Obtain all files in the specified directory (including hidden files ):
public static void getFile(){ File file=new File("D:"+File.separator); String[]str=file.list(); for (int i= 0; i< str.length; i++) { System.out.println(str[i]); } }
Determines whether the specified path is a directory.
public static void FileDirectory(){ File file=new File("D:"+File.separator+"IO"); String str= file.isDirectory() ? "yes":"no"; System.out.println(str); }
Searches all contents of a specified directory.
public static void print(File file ){ if(file!=null){ if(file.isDirectory()){ File [] fileArray=file.listFiles(); if(fileArray!=null){ for (int i = 0; i < fileArray.length; i++) { print(fileArray[i]); } } } else{ System.out.println(file); } } }
Address: http://www.manongjc.com/article/243.html
Related reading: