Program to Hide and unHide File or Directory (by executing CMD commands in java program) till java6 - file IO

Till java 6 there is no such direct method to hide a file.

In Unix - name of hidden file or directory name must start with a period (.)

In windows - For hiding file or directory , we must set the 'hidden' attribute to active in filesystem.
> For hiding in window use following CMD command -
attrib +h [file/directory]

C:\Users\ankitmittal01>attrib  +h  c:\myFile.txt



> For unHiding in window use following CMD command -
attrib -h [file/directory]

C:\Users\ankitmittal01>attrib  -h  c:\myFile.txt



We may use above commands to hide or unHide file or directory

Program to hide file till java 6  >
We must write a java program that could execute CMD command.

//Hide file;
Process process = Runtime.getRuntime().exec("cmd.exe /c attrib +h c:/myFile.txt");

import java.io.File;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class HideFile {
   public static void main(String... args) {   
          String fileName = "c:/myFile.txt";
          File fileToBeHidden = new File(fileName);
         
          try {
                
                 //Hide file;
                 Process process = Runtime.getRuntime().
                                          exec("cmd.exe /c attrib +h c:/myFile.txt");
                
                 //wait for process to get over (i.e. for file hiding)
                 process.waitFor();
                
          } catch (IOException e) {
                 e.printStackTrace();
          } catch (InterruptedException e) {
                 e.printStackTrace();
          }
      
          //Now, let's test whether file has been hidden or not
       boolean fileHidden = fileToBeHidden.isHidden();
         
          if(fileHidden)
                 System.out.println(fileName+" is hidden ");
          else
                 System.out.println(fileName+" isn't hidden ");
         
   }
}
/* OUTPUT
c:/myFile.txt renamed successfully to c:/myFileRenamed.txt
*/


unHide file till java 6  >
//unHide file
Process process = Runtime.getRuntime().exec("cmd.exe /c attrib -h c:/myFile.txt");          




RELATED LINKS>

Create File using createNewFile() method in java file IO


Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO


2 Program to Delete a Directory


Traverse a Directory (all sub-directories and files) in 2 ways




No comments:

Post a Comment