Как изменить имя файла java

Can we rename a file say test.txt to test1.txt ? If test1.txt exists will it rename ? How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for

Can we rename a file say test.txt to test1.txt ?

If test1.txt exists will it rename ?

How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?

Jonas Czech's user avatar

Jonas Czech

11.9k6 gold badges44 silver badges65 bronze badges

asked Jul 21, 2009 at 12:05

1

Copied from http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html

// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

if (file2.exists())
   throw new java.io.IOException("file exists");

// Rename file (or directory)
boolean success = file.renameTo(file2);

if (!success) {
   // File was not successfully renamed
}

To append to the new file:

java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);

Nathan's user avatar

Nathan

7,8127 gold badges47 silver badges72 bronze badges

answered Jul 21, 2009 at 12:09

Pierre's user avatar

PierrePierre

33.9k29 gold badges111 silver badges189 bronze badges

3

In short:

Files.move(source, source.resolveSibling("newname"));

More detail:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:

Suppose we want to rename a file to «newname», keeping the file in the same directory:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);

Community's user avatar

answered Nov 28, 2013 at 7:38

kr37's user avatar

kr37kr37

1,6211 gold badge11 silver badges7 bronze badges

6

You want to utilize the renameTo method on a File object.

First, create a File object to represent the destination. Check to see if that file exists. If it doesn’t exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.

If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it’s plain text, so I would look at the FileWriter.

answered Jul 21, 2009 at 12:08

Thomas Owens's user avatar

Thomas OwensThomas Owens

113k96 gold badges307 silver badges430 bronze badges

1

For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava’s Files.move.

Example:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.

EDIT:
I wrote this before I started using Java 7, which introduced a very similar approach. So if you’re using Java 7+, you should see and upvote kr37’s answer.

answered Jul 26, 2013 at 16:18

Zoltán's user avatar

ZoltánZoltán

21k13 gold badges92 silver badges133 bronze badges

0

Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }

answered Mar 17, 2013 at 3:45

Brandon's user avatar

BrandonBrandon

2,02320 silver badges25 bronze badges

This is an easy way to rename a file:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

answered Mar 4, 2015 at 16:00

senior's user avatar

seniorsenior

2,1566 gold badges36 silver badges54 bronze badges

1

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;

Path yourFile = Paths.get("path_to_your_filetext.txt");

Files.move(yourFile, yourFile.resolveSibling("text1.txt"));

To replace an existing file with the name «text1.txt»:

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);

answered Mar 24, 2017 at 11:27

Kirill Ch's user avatar

Kirill ChKirill Ch

5,2063 gold badges42 silver badges62 bronze badges

Try This

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult

Note :
We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.

Neuron's user avatar

Neuron

4,8435 gold badges36 silver badges54 bronze badges

answered Mar 25, 2018 at 18:05

anoopknr's user avatar

anoopknranoopknr

2,9872 gold badges21 silver badges32 bronze badges

1

Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}

answered Dec 26, 2018 at 21:21

V1ma-8's user avatar

V1ma-8V1ma-8

711 silver badge5 bronze badges

As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

About renaming a file in Java, see the documentation for the renameTo() method in class File.

answered Jul 21, 2009 at 12:08

Yuval's user avatar

YuvalYuval

7,93711 gold badges39 silver badges54 bronze badges

Files.move(file.toPath(), fileNew.toPath()); 

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.

Matt's user avatar

Matt

1,2981 gold badge12 silver badges31 bronze badges

answered Mar 30, 2017 at 13:12

Zhurov Konstantin's user avatar

Here is my code to rename multiple files in a folder successfully:

public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
    if(newName == null || newName.equals("")) {
        System.out.println("New name cannot be null or empty");
        return;
    }
    if(extension == null || extension.equals("")) {
        System.out.println("Extension cannot be null or empty");
        return;
    }

    File dir = new File(folderPath);

    int i = 1;
    if (dir.isDirectory()) { // make sure it's a directory
        for (final File f : dir.listFiles()) {
            try {
                File newfile = new File(folderPath + "\" + newName + "_" + i + "." + extension);

                if(f.renameTo(newfile)){
                    System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                } else {
                    System.out.println("Rename failed");
                }
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

and run it for an example:

renameAllFilesInFolder("E:\Downloads\Foldername", "my_avatar", "gif");

answered Sep 11, 2018 at 2:49

Tạ Anh Tú's user avatar

Tạ Anh TúTạ Anh Tú

1431 silver badge4 bronze badges

I do not like java.io.File.renameTo(…) because sometimes it does not renames the file and you do not know why! It just returns true of false. It does not thrown an exception if it fails.

On the other hand, java.nio.file.Files.move(…) is more useful as it throws an exception when it fails.

answered Mar 24, 2022 at 15:50

respenica's user avatar

Running code is here.

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Anh Pham's user avatar

Anh Pham

2,0909 gold badges18 silver badges29 bronze badges

answered Sep 23, 2017 at 6:04

Dinesh Kumar's user avatar

2

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

Сегодня мы рассмотрим способ переименования и перемещения файла в Java. Для начала рассмотрим это в теории: как работает метод, как использовать, а потом рассмотрим методы на практике.

Переименование файла в Java. Теория

Метод java.io.File renameTo(File dest) может быть использована для переименования или перемещения файла в Java. Этот метод возвращает true, если переименование файлов успешно, иначе она возвращает false. Некоторые операции зависят от платформы, например, переименование может потерпеть неудачу, если вы перемещаете файл из одной файловой системы в другую или, если файл с тем же именем уже существует в пункте назначения.

Переименование файла в Java. Практика

Вот пример программы, показывающий различные способы переименования файла в Java.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

package ua.com.prologistic;

import java.io.File;

public class RenameFileJava {

    public static void main(String[] args) {

        //здесь указываем абсолютный путь к файлу

        File file = new File(«/Users/prologistic/java.txt»);

        File newFile = new File(«/Users/prologistic/java1.txt»);

        if(file.renameTo(newFile)){

            System.out.println(«Файл переименован успешно»);;

        }else{

            System.out.println(«Файл не был переименован»);

        }

        //относительный путь к файлу

        file = new File(«DB.properties»);

        newFile = new File(«DB_New.properties»);

        if(file.renameTo(newFile)){

            System.out.println(«Файл переименован успешно»);;

        }else{

            System.out.println(«Файл не был переименован»);

        }

        //перемещаем файл с одной папки в другую

        file = new File(«/Users/prologistic/DB.properties»);

        newFile = new File(«DB_Move.properties»);

        if(file.renameTo(newFile)){

            System.out.println(«Файл перемещен успешно»);;

        }else{

            System.out.println(«Файл не был перемещен»);

        }

        //когда файл-источник не существует

        file = new File(«/Users/prologistic/xyz.txt»);

        newFile = new File(«xyz.properties»);

        if(file.renameTo(newFile)){

            System.out.println(«Файл перемещен успешно»);;

        }else{

            System.out.println(«Файл не был перемещен»);

        }

        // когда файл в папке-назначении уже существует

        file = new File(«/Users/prologistic/export.sql»);

        newFile = new File(«/Users/prologistic/java1.txt»);

        if(file.renameTo(newFile)){

            System.out.println(«Файл перемещен успешно»);

        }else{

            System.out.println(«Файл не был перемещен»);

        }

    }

}

Важный момент! Мы всегда должны проверять возвращаемое значение метода renameTo() для того, чтобы убедиться в успешном переименовании файла. Здесь все зависит от платформы и не бросает исключение, если переименование не удалось.

  1. Переименование файла с помощью метода renameTo() в Java
  2. Переименование файла с помощью метода move() в Java
  3. Переименование файла с помощью метода move() в Java
  4. Переименование файла с помощью библиотеки Apache commons в Java

Переименовать файл в Java

В этом руководстве рассказывается, как переименовать файл в Java, и перечислены некоторые примеры кодов, чтобы вы могли лучше понять тему.

Переименовать файл в Java довольно просто, поскольку Java предоставляет несколько встроенных методов в пакете java.io. Мы можем использовать эти методы для переименования файла и проверки других файловых операций. В этой статье мы будем использовать метод renameTo() класса File, метод move() класса Files и общую библиотеку Apache для переименования файла.

Переименование файла с помощью метода renameTo() в Java

В этом примере мы используем класс File для получения экземпляра файла, а затем, используя метод renameTo(), мы переименовали файл. Этот метод возвращает IOException, поэтому вы должны использовать соответствующий блок try-catch для обработки исключения. Метод renameTo() возвращает логическое значение, истинное или ложное, которое может использоваться, чтобы проверить, успешно ли переименован файл.

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");
    }
}

Выход:

Переименование файла с помощью метода move() в Java

Этот метод — еще одно решение для переименования файла. Здесь мы использовали метод move() класса Files, который можно использовать для переименования файла. См. Пример ниже:

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);
        }
    }
}

Переименование файла с помощью метода move() в Java

Метод move() имеет один метод перегрузки, который принимает путь к файлу в качестве второго параметра. Итак, если вы хотите переместить файл в другое место после процесса переименования, вы можете установить этот параметр в вызове функции.

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);
        }
    }
}

Переименование файла с помощью библиотеки Apache commons в Java

Если вы работаете с общей библиотекой Java Apache, вы можете использовать метод moveFile() класса FileUtils. Посмотрите пример программы здесь:

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();
        }
    }
}

В этом посте будет обсуждаться, как переименовать файл в Java.

Если файл успешно переименован, должно появиться сообщение об успехе. Если исходный файл не существует, NoSuchFileException должен быть выброшен, и если целевой файл уже присутствует, FileAlreadyExistsException следует бросить.

 
Существует несколько способов переименования файла в Java и с использованием сторонних библиотек, таких как Guava, Apache Commons IO и т. д. Они подробно обсуждаются ниже:

1. Использование File.renameTo() метод

До Java 7 мы могли вызывать renameTo() метод на File объект, чтобы переименовать его. Мы всегда должны проверять возвращаемое значение renameTo() чтобы убедиться, что операция переименования прошла успешно. Это связано с тем, что поведение этого метода по своей сути зависит от платформы, и он даже не создает IOException при неудаче.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import java.io.File;

import java.io.IOException;

import java.nio.file.FileAlreadyExistsException;

import java.nio.file.NoSuchFileException;

class Main

{

    public static void main(String[] args)

    {

        try {

            // исходный файл

            File file = new File(«demo.txt»);

            if (!file.exists()) {

                throw new NoSuchFileException(«The source file does not exist.»);

            }

            // целевой файл

            File dest = new File(«demo_success.txt»);

            if (dest.exists()) {

                throw new FileAlreadyExistsException(«The destination path exists.»);

            }

            boolean success = file.renameTo(dest);

            if (success) {

                System.out.println(«File successfully renamed»);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Скачать код

2. Использование Files.move() метод

С введением Класс файлов в Java 7 включены несколько статических методов, которые работают с файлами, каталогами или другими типами файлов. Чтобы переименовать (или переместить) файл в целевой файл, мы можем использовать Files.move() метод. Использование показано ниже:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

class Main

{

    public static void main(String[] args)

    {

        Path source = Paths.get(«demo.txt»);

        try {

            Files.move(source, source.resolveSibling(«demo_success.txt»));

            System.out.println(«File successfully renamed»);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Скачать код

3. Использование библиотеки Guava

Guava’s Files класс имеет несколько служебных методов для работы с файлами. Мы можем использовать его метод move() который перемещает файл с одного пути на другой. Этот метод работает и для переименования файла.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import com.google.common.io.Files;

import java.io.File;

import java.io.IOException;

class Main

{

    public static void main(String[] args)

    {

        try {

            // исходный файл

            File file = new File(«demo.txt»);

            // цель

            File dest = new File(«demo_success.txt»);

            Files.move(file, dest);

            System.out.println(«File successfully renamed»);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Скачать код

4. Использование Apache Commons IO

Мы также можем использовать FileUtils класс из библиотеки Apache Commons IO, который имеет moveFile() метод, который очень похож на метод Guava Files.move() метод.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import org.apache.commons.io.FileUtils;

import java.io.File;

import java.io.IOException;

class Main

{

    public static void main(String[] args)

    {

        try {

            // исходный файл

            File file = new File(«demo.txt»);

            // цель

            File dest = new File(«demo_success.txt»);

            FileUtils.moveFile(file, dest);

            System.out.println(«File successfully renamed»);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Скачать код

Это все о переименовании файла в Java.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Changing the name of the file is known as Renaming the file. Rename operation is possible using renameTo() method belongs to the File class in java.

    A. renameTo() Method

    The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.e. returns true if the file is renamed else returns false.

    Approach

    1. Create an object of the File class and replace the file path with the path of the directory.
    2. Create another object of the File class and replace the file path with the renaming path of the directory.
    3. Use renameTo() method.
    4. If rename operation successful then the function returns true.
    5. Else returns false.

    Below is the implementation of the above approach.

    Java

    import java.io.File;

    public class GFG {

        public static void main(String[] args)

        {

            File file = new File("/home/mayur/Folder/GFG.java");

            File rename = new File("/home/mayur/Folder/HelloWorld.java");

            boolean flag = file.renameTo(rename);

            if (flag == true) {

                System.out.println("File Successfully Rename");

            }

            else {

                System.out.println("Operation Failed");

            }

        }

    }

    Output:

    File Successfully Rename

    Before Program Execution

    After Program Execution

    B. move() Method

    Rename of file can be done using move the contents of the first file to a new file and deleting the previous file. Java is handling this operation using resolveSibiling method. It is used to resolve the given path against this path’s parent path

    Java

    import java.nio.file.*;

    import java.io.IOException;

    public class GFG {

        public static void main(String[] args)

            throws IOException

        {

            Path oldFile

                = Paths.get("/home/mayur/Folder/GFG.java");

            try {

                Files.move(oldFile, oldFile.resolveSibling(

                                        "HelloWorld.java"));

                System.out.println("File Successfully Rename");

            }

            catch (IOException e) {

                System.out.println("operation failed");

            }

        }

    }

    Output:

    File Successfully Rename

    Before Program Execution

    After Program Execution

    Details
    Written by  
    Last Updated on 30 July 2019   |   Print  Email

    To rename or move a file/directory in Java, you can use either the renameTo() method of a File  object in the old File I/O API, or the Files.move() method in the new Java NIO API.

     

    1. Rename File/Directory Example with renameTo() method

    You can use the renameTo() method to rename a file or directory to a new name which does not exist.

    The following example renames a file to a new name in the current directory:

    File sourceFile = new File("Notes.txt");
    File destFile = new File("Keynotes.txt");
    
    if (sourceFile.renameTo(destFile)) {
    	System.out.println("File renamed successfully");
    } else {
    	System.out.println("Failed to rename file");
    }

    As you can see in this example, the renameTo() method returns a boolean value indicating the renaming succeeded (true) or failed (false) — so you should always check its return value.

    If the destination file exists, the method returns false.

    The following example renames the directory “test” to “dist” in the current directory:

    File sourceFile = new File("test");
    File destFile = new File("dist");
    
    if (sourceFile.renameTo(destFile)) {
    	System.out.println("Directory renamed successfully");
    } else {
    	System.out.println("Failed to rename directory");
    }

    If the destination directory exists, the method return false.

     

    2. Move File Example with renameTo() method

    If the path of the destination File points to another directory, the source file will be moved. The following example moves a file from the current directory to another one (also renames it):

    File sourceFile = new File("CoverPhoto.png");
    File destFile = new File("D:/Photo/ProfilePhoto.png");
    
    if (sourceFile.renameTo(destFile)) {
    	System.out.println("File moved successfully");
    } else {
    	System.out.println("Failed to move file");
    }

    NOTE: You cannot use the renameTo() method to move directory, even the directory is empty.

    This method is platform-dependent and is not guaranteed to work in all cases. So it is recommended to use the Files.move() method in Java NIO as described below.

     

    3. Rename File/Directory Example with Files.move() method

    The static move() method of the Files class in the java.nio.file package is platform-independent and have options to replace the destination file if exists:

         Files.move(Path source, Path target, CopyOptions… options)

    This method returns the path to the target file, and throws exception if the operation failed.

    The following example renames a file in the current directory:

    Path source = Paths.get("Notes.txt");
    Files.move(source, source.resolveSibling("Keynotes.txt"));

    If the target file exists, this method throws java.nio.file.FileAlreadyExistsException. You can specify the option to replace the existing file like this:

    Path source = Paths.get("Notes.txt");
    Files.move(source, source.resolveSibling("Keynotes.txt"),
    			StandardCopyOption.REPLACE_EXISTING);

    The following example renames a directory to a new one:

    Path source = Paths.get("photo");
    Files.move(source, source.resolveSibling("photos"));

    If the target dir exists, it throws FileAlreadyExistsException. You can fore to replace the existing directory with the copy option:

    Path source = Paths.get("photo");
    Files.move(source, source.resolveSibling("photos"),
    				StandardCopyOption.REPLACE_EXISTING);

    However, this works only if the target directory is not empty. Otherwise, it throws java.nio.file.DirectoryNotEmptyException.

     

    4. Move File/Directory Example with Files.move() method

    The following example illustrates how to move a file from the current directory to another (keeping the same file name) and replace the existing file:

    Path source = Paths.get("CoverPhoto.png");
    Path newdir = Paths.get("D:/Photo");
    Files.move(source, newdir.resolve(source.getFileName()), 
    			StandardCopyOption.REPLACE_EXISTING);

    And you can move an empty directory to another location, for example:

    Path source = Paths.get("test");
    Path newdir = Paths.get("D:/Photo");
    Files.move(source, newdir.resolve(source.getFileName()));

    NOTE: You can move only empty directory and replace existing directory if it is also empty. In either a directory is not empty, a DirectoryNotEmptyException is thrown.

     

    API References:

    • File.renameTo() method Javadoc
    • Files.move() method Javadoc

     

    Related File IO Tutorials:

    • How to list files and directories in a directory in Java
    • Calculate total files, sub directories and size of a directory
    • How to copy a directory programmatically in Java

     

    Other Java File IO Tutorials:

    • How to Read and Write Text File in Java
    • How to Read and Write Binary Files in Java
    • Java IO — Common File and Directory Operations Examples
    • Java Serialization Basic Example
    • Understanding Java Externalization with Examples
    • How to execute Operating System Commands in Java
    • 3 ways for reading user’s input from console in Java
    • File change notification example with Watch Service API
    • Java Scanner Tutorial and Code Examples
    • How to compress files in ZIP format in Java
    • How to extract ZIP file in Java

    About the Author:

    Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

    Add comment

    Понравилась статья? Поделить с друзьями:
  • Как изменить интерфейс opera gx
  • Как изменить имя файла exe
  • Как изменить интерфейс mach3
  • Как изменить имя учетной записи через реестр
  • Как изменить интерфейс gmail