How to rename file in Java

2 Answers

0 votes
import java.io.File;

class program {
    public static void main(String[] args) {
        try {
            File file_old = new File("d:\\data.bin");
            File file_new = new File("d:\\data_new_name.bin");
                      
            if (file_new.exists()) {
                throw new java.io.IOException("d:\\data_new_name.bin - exists");
            }
          
            boolean success = file_old.renameTo(file_new);
                      
            if (!success) {
                System.out.println("Rename error");
            } else {
                System.out.println("Rename success");
            }
        }    
        catch (Exception e) {
            System.out.println("Error rename file: " + e.getMessage());   
        }
    }
}
 
   
/*
run:
   
Rename success
   
*/

 



answered Aug 26, 2015 by avibootz
edited Apr 23, 2024 by avibootz
0 votes
import java.io.File;

class program {
    public static void main(String[] args) {
        try {
            File oldName = new File("d://data.txt");
            File newName = new File("d://data-old.txt");
 
            boolean b = oldName.renameTo(newName);
 
            if (b) {
                System.out.println("File renamed");
            } else {
                System.out.println("File not renamed");
            }
 
        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

  
/*
run:
      
File renamed
   
*/

 



answered Apr 23, 2024 by avibootz

Related questions

1 answer 145 views
145 views asked Nov 19, 2016 by avibootz
1 answer 130 views
130 views asked Aug 22, 2023 by avibootz
1 answer 173 views
173 views asked Jul 12, 2020 by avibootz
1 answer 222 views
222 views asked Mar 10, 2020 by avibootz
1 answer 240 views
1 answer 209 views
209 views asked Jun 9, 2018 by avibootz
1 answer 216 views
216 views asked Aug 26, 2015 by avibootz
...