JAVA – Hot To Rename a File or Directory.

A quick script to re-name a file or folder:

Import required:

import java.io.File;

Code:

try{       
        // File name (or directory) of the file to be renamed
        File file = new File(“c:/file1.txt”);
        // New File name (or directory)
        File file2 = new File(“c:/file2.txt”);
        // Rename file (or directory)
        file.renameTo(file2);
    }catch(Exception e){
        e.printStackTrace();
    }

Advertisements

JAVA – How To Get The Current Directory

The following script gets the current directory at runtime:

import java.io.File;

public class CurrentDir {
   public static void main (String args[]) {
     File dir = new File (“.”);
     try {
       System.out.println (“Current Directory : ” + dir.getCanonicalPath());       }
     catch(Exception e) {
       e.printStackTrace();
       }
     }
}

The same logic can be used to get the parent to the current directory:

import java.io.File;

public class ParentDir {
   public static void main (String args[]) {
     File dir = new File (“..”);
     try {
       System.out.println (“Parent  Directory : ” + dir.getCanonicalPath());
       }
     catch(Exception e) {
       e.printStackTrace();
       }
     }
}