This article explains the basic operations of Java files, including Java to create files and folders, Java delete files, Java to get all the files of the specified directory, Java to determine whether the specified path is a directory, and the Java search for the entire contents of the specified directory. Take a look at the example below.
Create a file
The two constants of File (File.separator, File.pathseparator). It is possible to use \ to split directly under Windows. But under Linux it's not. So, to make our code cross-platform, more robust, so, we all 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 trycatch (IOException e) {System.out.println ("IO exception") under Windows ); E.printstacktrace (); }}
Delete a file
Public Static void =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 (); }
Get all files (including hidden files) for the specified directory:
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); }
Search all contents of a specified directory
Public Static voidprint (file file) {if(file!=NULL) {if(File.isdirectory ()) {file [] Filearray=File.listfiles (); if(filearray!=NULL) { for(inti = 0; i < filearray.length; i++) {print (filearray[i]); }}}Else{System.out.println (file); }}}
Original address: http://www.manongjc.com/article/243.html
Related reading:
- Java writes a file using the Write () method
- Java readLine () Read file contents
- Java Delete () deleting files
- Java uses the read and write methods to copy the contents of a file to another file
- Java uses the FileWriter method to append data to a file
- Java uses the Createtempfile () method to create temporary files
- How Java modifies the last modified date of a file
- How Java gets the file size
- How to rename a file in Java
- How Java sets file Read-only
- Java uses the Exists () method to detect whether a file exists
- How Java creates files in the specified directory
- How Java gets file modification time
- Java Create file instance
- Java compare two file paths in the same directory
Create, delete files and folders for Java file operations