In Java, renaming a file or folder is simple, because the Java file class already encapsulates the Renameto method.
This method is used to modify the name of the file or folder. For example, the following programs:
[Java]View PlainCopy
- Import java.io.*;
- Public class Renametest {
- public static void Main (string[] args) {
- //The path of the original file you want to name
- File File = new file ("f:/a/a.xlsx");
- //Change the original file to F:\a\b.xlsx, where the path is necessary. Note
- File.renameto (new File ("f:/a/b.xlsx"));
- //The path of the original folder you want to name
- File File1 = new File ("f:/a");
- //Change the original folder to a, where the path is necessary. Note
- File1.renameto (new File ("f:/b"));
- }
- }
Once run, the F:/A/A.XLSX will be renamed to F:/a/b.xlsx, and the f:/a folder will be renamed to F:/b.
Note that under Windows, folders and file names are case-insensitive.
So f:/a and f:/a are actually matter.
In fact, folder renaming can also be written to a shorter point, even this file class declaration is not.
Rename f:/a/a.xlsx to F:/a/b.xlsx and write this straight:
[Java]View PlainCopy
- Import java.io.*;
- Public class Renametest {
- public static void Main (string[] args) {
- //Rename the f:/a/a.xlsx original file to F:/a/b.xlsx, where the path is necessary. Note
- New File ("F:/a/a.xlsx"). Renameto (new file ("f:/a/b.xlsx"));
- }
- }
Then, it is worth noting that the previous parent path of the renaming file must be the same, that is, the following is not the way:
[Java]View PlainCopy
- Import java.io.*;
- Public class Renametest {
- public static void Main (string[] args) {
- New File ("F:/a/a.xlsx"). Renameto (new file ("c:/a/b.bmp"));
- }
- }
After execution, the Renameto method returns False, and then the system's folder does not change.
"Java" renames a file or folder