"Java" renames a file or folder

Source: Internet
Author: User

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
  1. Import java.io.*;
  2. Public class Renametest {
  3. public static void Main (string[] args) {
  4. //The path of the original file you want to name
  5. File File = new file ("f:/a/a.xlsx");
  6. //Change the original file to F:\a\b.xlsx, where the path is necessary. Note
  7. File.renameto (new File ("f:/a/b.xlsx"));
  8. //The path of the original folder you want to name
  9. File File1 = new File ("f:/a");
  10. //Change the original folder to a, where the path is necessary. Note
  11. File1.renameto (new File ("f:/b"));
  12. }
  13. }

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
  1. Import java.io.*;
  2. Public class Renametest {
  3. public static void Main (string[] args) {
  4. //Rename the f:/a/a.xlsx original file to F:/a/b.xlsx, where the path is necessary. Note
  5. New File ("F:/a/a.xlsx"). Renameto (new file ("f:/a/b.xlsx"));
  6. }
  7. }

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
    1. Import java.io.*;
    2. Public class Renametest {
    3. public static void Main (string[] args) {
    4. New File ("F:/a/a.xlsx"). Renameto (new file ("c:/a/b.bmp"));
    5. }
    6. }

After execution, the Renameto method returns False, and then the system's folder does not change.

"Java" renames a file or folder

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.