English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Java

Controle de fluxo Java

Java Array

Java Orientação a Objetos (I)

Java Orientação a Objetos (II)

Java Orientação a Objetos (III)

Tratamento de Exceções Java

Java Lista (List)

Java Fila (Queue)

Java Mapa (Map)

Java Conjunto (Set)

Java Entrada/Saída (I/O)/O)

Reader Java/Writer

Outros tópicos do Java

Renomear arquivo no programa Java

Java Examples

Neste tutorial, vamos aprender a renomear arquivos usando Java.

emArquivo JavaA classe fornece o método renameTo() para alterar o nome do arquivo. Se a operação de renomeação for bem-sucedida, retorna true, caso contrário, retorna false.

Exemplo: Renomear arquivo usando Java

import java.io.File;
class Main {
  public static void main(String[] args) {
    //Criar um objeto de arquivo
    File file = new File("oldName");
      
    //Criar um arquivo
    try {
      file.createNewFile();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
    //Criar um objeto que contém o novo nome do arquivo
    File newFile = new File("newName");
    //Mudar o nome do arquivo
    boolean value = file.renameTo(newFile);
    if(value) {
      System.out.println("O nome do arquivo foi alterado.");
    }
    else {
      System.out.println("The name cannot be changed.");
    }
  }
}

In the above example, we created a file object named file. This object saves information about the specified file path.

File file = new File("oldName");

Then, we create a new file using the specified file path.

//Create a new file with the specified path
file.createNewFile();

Here, we created another file object named newFile. This object saves information about the specified file path.

File newFile = new File("newFile");

To change the file name, we used the renameTo() method. The name specified by the newFile object is used to rename the file specified by the file object.

file.renameTo(newFile);

If the operation is successfulA message will be displayed as follows.

The name of the file has been changed.

If the operation cannot be successfulA message will be displayed as follows.

The name cannot be changed.

Java Examples