Как переименовать файл в java
Перейти к содержимому

Как переименовать файл в java

  • автор:

Rename a File in Java

Rename a File in Java

  1. Rename a File Using the renameTo() Method in Java
  2. Rename a File Using the move() Method in Java
  3. Rename a File Using the move() Method in Java
  4. Rename a File Using the Apache commons Library in Java

This tutorial introduces how to rename a file in Java and lists some example codes for you to understand the topic further.

Renaming a file in Java is pretty easy as Java provides several built-in methods in the java.io package. We can use these methods to rename a file and check other file operations as well. In this article, we will use the renameTo() method of the File class, the move() method of the Files class, and the Apache commons library to rename the file.

Rename a File Using the renameTo() Method in Java

In this example, we are using the File class to get the instance of the file, and then by using the renameTo() method, we renamed the file. This method returns an IOException , so you must use a proper try-catch block to handle the exception. The renameTo() method returns a boolean value, either true or false, that can be used to check whether a file is renamed successfully.

import java.io.File; import java.io.IOException; public class SimpleTesting   public static void main(String[] args) throws IOException   File file1 = new File("abc.txt");  File file2 = new File("abcd.txt");  if (file2.exists())  throw new java.io.IOException("file exists");  boolean success = file1.renameTo(file2);  if (success)   System.out.println("File Rename successfuly");  > else  System.out.println("File is not Rename");  > > 
File Rename successfuly 

Rename a File Using the move() Method in Java

This method is another solution to rename a file. Here, we used the move() method of the Files class, which can be used to make a file renamed. See the example below:

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class SimpleTesting   public static void main(String[] args)   try   Path source = Paths.get("/file-location/abc.txt");  Files.move(source, source.resolveSibling("/file-location/abcd.txt"));  > catch (Exception e)   System.out.println(e);  >  > > 

Rename a File Using the move() Method in Java

The move() method has one overloading method that takes a file-path as a second parameter. So, if you want to move a file to another location after the rename process, you can set this parameter in the function call.

import java.io.File; import java.nio.file.Files; public class SimpleTesting   public static void main(String[] args)   try   File newFile = new File(new File("/file-location/abc.txt").getParent(), "abcd.txt");  Files.move(new File("/file-location/abc.txt").toPath(), newFile.toPath());  > catch (Exception e)   System.out.println(e);  >  > > 

Rename a File Using the Apache commons Library in Java

If you are working with the Apache commons Java library, you can use the moveFile() method of the FileUtils class. Check the example program here:

import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class SimpleTesting   public static void main(String[] args)   File file = new File("/file-location/abc.txt");  String newName = "abcd.txt";  String newFilePath = file.getAbsolutePath().replace(file.getName(), "") + newName;  File newFile = new File(newFilePath);  try   FileUtils.moveFile(new File("/file-location/abc.txt"), newFile);  > catch (IOException e)   e.printStackTrace();  >  > > 

Related Article — Java File

  • Remove Line Breaks Form a File in Java
  • FileFilter in Java
  • File Separator in Java
  • Get File Size in Java
  • Read Bytes From a File in Java
  • Delete Files in a Directory Using Java

Copyright © 2023. All right reserved

Как переименовать файл files java

Переименовать файл можно с помощью метода renameTo , который вернет true или false в зависимости от успешности операции :

String fileName = "output.txt"; File file = new File(fileName); File newfile = new File("new_output.txt"); if(file.renameTo(newfile))  // переименование прошло успешно > else  // переименование не удалось > 

Java не удается переименовать файл

У меня есть массив байт, я создаю файл и записываю массив байт в этот файл, потом закрываю запись. Как запись закрыта я хочу переименовать расширение файла. Мой код:

FileOutputStream newFile = new FileOutputStream(rb_Path[0]+"\\"+file_id+".d"); //было .dat //Записать массив полученных байт в новый файл .dat newFile.write(byteNewFile); newFile.flush(); //Закрываем создание нового файла newFile.close(); File file_d = new File(rb_Path[0]+"\\"+file_id+".d"); //File file_dat = new File(rb_Path[0]+"\\"+file_id+".dat"); //file.d переименовать в file.dat boolean isRenamed = file_d.renameTo(new java.io.File(rb_Path[0] + "\\" + file_id + ".dat")); System.out.println(isRenamed); 

Но получаю false. И как итог не переименовался файл (1234.d на 1234.dat). Также пробовал так:

File file_d = new File(rb_Path[0]+"\\"+file_id+".d"); //Создан File file_dat = new File(rb_Path[0]+"\\"+file_id+".dat"); //Не создан, служит объектом для rename //file.d переименовать в file.dat boolean isRenamed = file_d.renameTo(file_dat); System.out.println(isRenamed); 
  • rb_Path[0] — не имеет некорректных символов.
  • file_id — это int, например 1234

Поэтому даже не знаю как быть.

Подскажите пожалуйста как можно решить такую задачу. Может стоит и вовсе делать все по другому? У кого есть решение? Заранее спасибо большое.

Как переименовать файл в java

Поиск и переименование файлов на JAVA

Опубликовано 11 февраля, 2013 автором Jeyhun Alekberov

Для переименования конкретного файла в java достаточно воспользоваться следующим кодом:

import java.io.File; public class Main < public static void main(String [] args)< java.io.File file = new java.io.File("D:\\test.txt"); // создаем объект на файл test.txt if(file.exists())< // если файл существует, то переименовываем его file.renameTo(new java.io.File("D:\\main.java")); >else < System.out.println("File not found!"); >> >

Немного усложним: допустим у нас имеется некоторая папка D:\Test\. В ней содержатся разные файлы, в том числе и в формате *.txt и нам нужно сменить их формат скажем на *.java. Иначе говоря нужно переименовать их. Для начала создаем массив объектов типа File на файлы находящиеся в директории. Затем создаем цикл в котором читаем название каждого файла и если он имеет расширение *.txt , то меняем его на *.java. Собственно вот сам код:

import java.io.File; public class Main < public static void main(String [] args)< File[] filesList; File filesPath = new java.io.File("D:\\Test\\"); // создаем объект на папку с файлами filesList = filesPath.listFiles(); // записываем файлы из папки в массив объектов типа File for(int i=0; i> > >

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *