Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » » » File Concept Simplified In Java

File is an important concept while doing any I/O operation using java. Frequently to read and write to a storage we use file. This is placed inside Java.io package.

In UNIX operating system, there is no separate thing defined for files and directories. Java File IO concept is defined and implemented based on UNIX. Hence File IO operations are same for file and directories.
File f=new File("path\\filename.txt");
This statement in java will not create a new file instead it will check if there is any physical file exists in the given path. If so it will simply point to that file.If not it will do anything.

File fl=new File("c:\\test.txt");
System.out.println(fl.exist());
//this will simply return false
fl.createNewFile();
//This will create a file
System.out.println(fl.exist());
//Now it will return true


Similarly for directories also we can use the same commands...
File fl=new File("c:\\test");
System.out.println(fl.exist());
//this will simply return false
fl.mkdir();
//This will create a directory inside C drive named as test
System.out.println(fl.exist());
//Now it will return true

Let us check the constructors available in file...
File f=new File(String FileName)
// Checks if a file is present in the current working directory
File f=new File(String subDirectory,string fileName) 
//This will create a file in given directory
// if the path is not given as a part of FileName  
File f=new File(File SubDirectory,String FileName)
//This will create a file in the sub directory under current directory
// if the path is not given as a part of FileName 

Important methods for file:
  • boolean exists() This method checks if the physical file is available or not. If that is available it returns true or else it returns false
  • boolean createNewFile() This method checks if the physical file is available or not. If it is available it will return false without creating a new one. Else it will create a new file with the name provided.
  • boolean mkdir()  Same as above.
  • boolean isFile()  If the file object points to a valid physical file then it returns true else it will return false.
  • boolean isDirectory() Same as above.
  • String[] list() It returns all files and subdirectories present in specific sub directory.
  • long length() It returns the number of character presents in a file.
  • boolean delete() if file object points to a physical file and is able to delete the same, it will return true else will return false.

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply