Class File
The File class is in the java.io package. IO stands for input and output, input and output.
Represents files and directories that are not platform related.
You can create, delete, rename, but you cannot access the file content.
Constants in the File class:
import java.io.File; public class TestFileConst { public static void main(String[] args) { String s = ""; // File separator: win backslash (\) linux forward slash (/) s = File.separator; System.out.println(s); // Path separator: win semicolon (;) linux colon (:) s = File.pathSeparator; System.out.println(s); } }
The parameter path in the File construction method:
|--It can be a file or a folder
|--It can be a relative path or an absolute path
|--It can exist or not (just encapsulating the path as a File object)
import java.io.*; /** * File Basic methods of class */ public class T010File Basic method { public static void main(String[] args) throws IOException { String userDir = System.getProperty("user.dir"); System.out.println(userDir); File file = new File(userDir); System.out.println("Is it a document?" + file.isFile()); System.out.println("Is it a catalog?" + file.isDirectory()); System.out.println("How many bytes is the file?" + file.length()); System.out.println("Filename [ getName]" + file.getName());//Folder returned 0 System.out.println("Absolute path[ getAbsoluteFile]" + file.getAbsoluteFile()); System.out.println("Upper path[ getParent]" + file.getParent()); System.out.println("=====Temporary file====="); File fileTemp = File.createTempFile("tmp_", ".txt", file); System.out.println("Temporary file:" + fileTemp.getAbsolutePath()); System.out.println("Temporary documents[ exists]: " + fileTemp.exists()); System.out.println("JVM Delete temporary files on exit"); fileTemp.deleteOnExit(); } }
Recursively scan folders
import java.io.*; public class folderScanner { public static void main(String[] args) { try { getFiles("C:\\Program Files\\Java"); } catch (IOException e) { e.printStackTrace(); } } private static void getFiles(String path_src) throws IOException { File pathS_Files = new File(path_src); if (!pathS_Files.isDirectory()) { System.out.println("The folder path entered is wrong!"); return; } File[] listFiles = pathS_Files.listFiles(); for (int i = 0; i < listFiles.length; i++) { File f1 = listFiles[i]; if (f1.isDirectory()) { // If it's a folder, keep searching getFiles(f1.getAbsolutePath()); } else if (f1.isFile()) { System.out.println(f1.getAbsolutePath()); } } } }
Upgrading: filtering files
The public File[] listFiles(FileFilter filter) method can filter the obtained files. The FileFilter interface needs to be implemented.
Most of the code in the following example is the same as the above example, except that FileFilter is added.
import java.io.*; /** * ↓↓↓Filter for abstract pathnames (that is, File objects). */ class MyFileFilter implements FileFilter { @Override // accept: a method of filtering files // Parameter: every File (File object) obtained by traversing the directory public boolean accept(File pathname) { if (pathname.isDirectory()) { // Yes folder, release return true; } else if (pathname.getName().toLowerCase().endsWith(".txt")) { // It's a matching document, release return true; } else { // Other files, filtering out return false; } } } public class folderScanner { public static void main(String[] args) { try { getFiles("C:\\Program Files\\Java"); } catch (IOException e) { e.printStackTrace(); } } private static void getFiles(String path_src) throws IOException { File pathS_Files = new File(path_src); if (!pathS_Files.isDirectory()) { System.out.println("The folder path entered is wrong!"); return; } // ↓↓↓ // Core code of this example: two versions (in fact, an anonymous inner class version can also be written) // File[] listFiles = pathS_Files.listFiles(new MyFileFilter()); // *There is only one method for FileFilter interface, so Lambda expression can be used: File[] listFiles = pathS_Files.listFiles((pathname) -> { if (pathname.isDirectory()) { // Yes folder, release return true; } else if (pathname.getName().toLowerCase().endsWith(".txt")) { // It's a matching document, release return true; } else { // Other files, filtering out return false; } }); // ↑↑↑ for (int i = 0; i < listFiles.length; i++) { File f1 = listFiles[i]; if (f1.isDirectory()) { // If it's a folder, keep searching getFiles(f1.getAbsolutePath()); } else if (f1.isFile()) { System.out.println(f1.getAbsolutePath()); } } } }
Exercise: input the path in the console, scan the folder, and count the total number of files, folders, and java code files.
Create and delete dependencies
package day0422; import java.io.File; import java.io.IOException; public class TestNewFile { public static void main(String[] args) { File f = new File("2.txt"); try { // Create new file, success is true, do not overwrite // Folder must exist, otherwise throw exception boolean create = f.createNewFile(); System.out.println(create); } catch (IOException e) { e.printStackTrace(); } // ---------------------------- // Create single level folder f = new File("2"); boolean mkdir = f.mkdir(); System.out.println(mkdir); // Create a multi-level folder (4.txt as the folder name) f = new File("2\\3\\4.txt"); boolean mkdirs = f.mkdirs(); System.out.println(mkdirs); // Delete files or folders (last level) // |--There is content in the last level folder, do not delete, return false // |--Path does not exist, return false // |--No recycle bin boolean delete = f.delete(); System.out.println(delete); } }
Application: create a file. If there is a file with the same name, delete it.
import java.io.*; public class T011File Delete if there is nothing { public static void main(String[] args) { File f1 = new File("tmp_File Yes and No..txt"); if (f1.exists()) { boolean delete = f1.delete(); System.out.println("To delete a file with the same name:" + delete); } try { boolean ret = f1.createNewFile(); System.out.println("To create a file:" + ret); } catch (IOException e1) { e1.printStackTrace(); } } }
nio.file package of Java 7
Class Paths
Similar to the File class
import java.nio.file.Path; import java.nio.file.Paths; public class T031nioPaths { public static void main(String[] args) throws Exception { String _user_dir = System.getProperty("user.dir"); // Get Path object Path _path = Paths.get(_user_dir); System.out.println(".toAbsolutePath()[]" + _path.toAbsolutePath()); // Root path System.out.println(".getRoot()[]" + _path.getRoot()); // Included paths (excluding root paths) int nameCount = _path.getNameCount(); for (int i = 0; i < nameCount; i++) { System.out.println("\t" + _path.getName(i)); } System.out.println(".getNameCount()Number of paths included []" + nameCount); // Building Path objects with multiple strings Path path2 = Paths.get("g:", "publish", "codes"); System.out.println(path2); } }
Class Files
import java.io.FileOutputStream; import java.io.OutputStream; import java.nio.charset.*; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class T032nioFiles { public static void main(String[] args) throws Exception { System.out.println("=====Files.copy:Copy file====="); Path _path source file = Paths.get("testRead.dat"); OutputStream os = new FileOutputStream("Files.copy.txt");// Under working path long copy = Files.copy(_path source file, os); System.out.println("Files.copy() return value = " + copy); System.out.println("Files.size(source file): " + Files.size(_path source file)); System.out.println("=====Files.readAllLines:read file====="); List<String> lines = Files.readAllLines(_path source file, Charset.forName("utf-8")); System.out.println("Files.readAllLines()Rows read——" + lines.size()); System.out.println("=====Files.write:Writing file====="); List<String> _list = new ArrayList<>(); _list.add("The people of Xiniu Hezhou, who are not greedy but not killed, Nourish Qi and have spirit, though they are not true, everyone can live a long life."); _list.add("However, those who support the southern continent are greedy for prostitution and pleasure, killing more and seizing more, which is the so-called fierce field of speech, and it is not a sea of evil."); Path _pathW = Files.write(Paths.get("Files.write.txt"), _list, Charset.forName("gbk")); System.out.println("Write to file——" + _pathW.toAbsolutePath()); System.out.println("=====FileStore:See C Disk space====="); FileStore cStore = Files.getFileStore(Paths.get("C:")); System.out.println("C:Shared space:" + cStore.getTotalSpace()); System.out.println("C:Free space:" + cStore.getUsableSpace()); // ------------------------------------- System.out.println("=====Use Java 8 Of Stream API List all files and subdirectories in the current directory====="); Files.list(Paths.get(".")).forEach(path -> System.out.println(path)); // ------------------------------------- System.out.println("=====Use Java 8 Of Stream API Read file contents====="); Files.lines(_path source file, Charset.forName("utf-8")).forEach(line -> System.out.print(line)); } }