In Java, the File class is a very commonly used class. It provides a series of methods to help us perform file operations, such as file creation, deletion, renaming, etc. This article will introduce how to use the File function in Java for file operations.
1. Common methods of the File class
When using the File class, we can use the following common methods:
2. Usage Example
Next, let us use a specific example to demonstrate how to use the above method to perform file operations.
We can use the mkdirs() method of the File class to create a folder named "test".
File file = new File("test"); if(!file.exists()){ file.mkdirs(); }
We can use the createNewFile() method of the File class to create a file named "hello.txt" in the folder.
File file = new File("test/hello.txt"); if (!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } }
We can use the renameTo() method of the File class to rename a file or folder.
File oldName = new File("test/hello.txt"); File newName = new File("test/hello_world.txt"); oldName.renameTo(newName);
We can use the delete() method of the File class to delete a file or folder.
File file = new File("test/hello_world.txt"); if (file.exists()){ file.delete(); }
We can use the exists() method of the File class to determine whether a file or folder exists.
File file = new File("test/hello_world.txt"); if (file.exists()){ System.out.println("文件存在"); } else { System.out.println("文件不存在"); }
We can use the length() method of the File class to get the size of a file or folder.
File file = new File("test/hello_world.txt"); long fileSize = file.length(); System.out.println("文件大小为" + fileSize + "B");
We can use the getAbsolutePath() method of the File class to get the absolute path of a file or folder, using The getParent() method gets the parent path.
File file = new File("test/hello_world.txt"); System.out.println("文件的绝对路径为:" + file.getAbsolutePath()); System.out.println("文件的父路径为:" + file.getParent());
3. Summary
Through the above examples, we have learned how to use the File class to perform file operations, such as creating files and folders, deleting files and folders, and renaming files and folders. , obtain the absolute path, parent path and size of files and folders and other operations. When using the File class, you need to pay attention to the way the path is written and the validity of the path. You also need to pay attention to file access permissions to avoid abnormal file operations.
The above is the detailed content of How to use File function in Java for file operations. For more information, please follow other related articles on the PHP Chinese website!